let code = require('../../../constant/code');
let commonDao = require('../../../dao/commonDao');
let userDao = require('../../../dao/userDao');
let userInfoServices = require('../../../services/userInfoServices');
let utils = require('../../../util/utils');
let logger = require('pomelo-logger').getLogger("operate");
let enumeration = require('../../../constant/enumeration');
let DAY_MS = 24 * 60 * 60 * 1000;
let WEEK_MS = 4 * 7 * DAY_MS;
let pomelo = require('pomelo');

let moment = require('moment');
let userList = [];


module.exports = function (app) {
    return new Handler(app);
};

let Handler = function (app) {
    this.app = app;
};

function getSimData(obj) {
    let data = JSON.parse(JSON.stringify(obj));
    delete data['__route__'];
    return JSON.stringify(data);
}

//更新机器人分数
Handler.prototype.updateRobotScore = async function (msg, session, next) {

    logger.info(`[updateRobotScore] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.count || !msg.userList) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });

        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }

        //只能盟主或者管理员才有此功能
        if (unionData && (userUnionInfoItem.manager || session.uid == unionData.ownerUid)) {

            // 查询用户数据
            let userData = await userDao.getUnlockUserDataAndLock(session.uid);
            if (!userData) {
                next(null, {
                    code: code.REQUEST_DATA_ERROR
                });
                return;
            }

            // 判断是否在联盟中
            let userUnionInfoItem = null;
            for (let i = 0; i < userData.unionInfo.length; ++i) {
                if (userData.unionInfo[i].unionID === msg.unionID) {
                    userUnionInfoItem = userData.unionInfo[i];
                    break;
                }
            }
            msg.count = parseInt(msg.count) || 0;
            // 判断积分是否足够
            let userList = msg.userList || [];
            let total = msg.count * userList.length;
            if (!userUnionInfoItem || (userUnionInfoItem.score < total)) {
                await userDao.unlockUserData(session.uid);
                next(null, {
                    code: code.NOT_ENOUGH_SCORE
                });
                return;
            }

            //盟主扣分
            let newUserData = await userDao.updateUserDataAndUnlock({
                uid: session.uid,
                "unionInfo.unionID": msg.unionID
            }, {
                $inc: {
                    "unionInfo.$.score": -total
                }
            });
            let scoreChangeRecordArr = [];
            //批量
            for (let i = 0; i < userList.length; i++) {

                let curUid = userList[i];
                //给机器人改分
                let newMemberData = await userDao.updateUserDataAndUnlock({
                    uid: curUid,
                    "unionInfo.unionID": msg.unionID
                }, {
                    $inc: {
                        "unionInfo.$.score": Math.abs(msg.count)
                    }
                });

                let unionInfoItem = newMemberData.unionInfo.find(item => item.unionID == msg.unionID);
                // 添加修改记录
                let createData = {
                    uid: session.uid,
                    nickname: userData.nickname,
                    avatar: userData.avatar,
                    gainUid: curUid,
                    gainNickname: newMemberData.nickname,
                    gainAvatar: newMemberData.avatar,
                    gainScore: unionInfoItem.score,
                    unionID: msg.unionID,
                    count: Math.abs(msg.count),
                    createTime: Date.now()
                };
                commonDao.createData('scoreModifyRecordModel', createData).catch(e => {
                    logger.error(e.stack)
                });
                if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                    unionInfo: newMemberData.unionInfo
                }).catch(e => {
                    logger.error(e.stack)
                });

                // 存储分数变化记录
                let newUnionInfo = newMemberData.unionInfo.find(function (e) {
                    return e.unionID === msg.unionID;
                });

                scoreChangeRecordArr.push({
                    uid: newUserData.uid,
                    nickname: newUserData.nickname,
                    unionID: msg.unionID,
                    changeCount: -msg.count,
                    leftCount: newUnionInfo.score,
                    leftSafeBoxCount: newUnionInfo.safeScore,
                    leftSaveBoxCount: newUnionInfo.saveScore,
                    changeType: enumeration.scoreChangeType.MODIFY_LOW,
                    describe: msg.count > 0 ? "我增加[" + newMemberData.uid + "]积分" : "我减少[" + newMemberData.uid + "]积分",
                    createTime: Date.now()
                });
                let newMemberUnionInfo = newMemberData.unionInfo.find(function (e) {
                    return e.unionID === msg.unionID;
                });
                scoreChangeRecordArr.push({
                    uid: newMemberData.uid,
                    nickname: newMemberData.nickname,
                    unionID: msg.unionID,
                    changeCount: msg.count,
                    leftCount: newMemberUnionInfo.score,
                    leftSafeBoxCount: newMemberUnionInfo.safeScore,
                    leftSaveBoxCount: newMemberUnionInfo.saveScore,
                    changeType: enumeration.scoreChangeType.MODIFY_UP,
                    describe: msg.count > 0 ? "[" + newUserData.uid + "]增加我的积分" : "[" + newUserData.uid + "]减少我的积分",
                    createTime: Date.now()
                });

            }
            //0721新的变化记录
            await commonDao.createDataArr("userScoreDetailModel", scoreChangeRecordArr).catch(e => {
                logger.error(e.stack)
            });
            next(null, {
                code: code.OK,
                updateUserData: {
                    unionInfo: newUserData.unionInfo
                }
            });
            logger.info(`[updateRobotScore] operate success`);
        } else {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
    } catch (e) {
        logger.error(`[updateRobotScore]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//新增禁止同桌功能
Handler.prototype.addUserBlockRule = async function (msg, session, next) {

    logger.info(`[addUserBlockRule] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[addUserBlockRule] ownerUid = ${unionData.ownerUid} isManager = ${userUnionInfoItem.manager} sessionUid = ${session.uid}`);
        //如果不是管理员或者盟主
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //新增一条记录
        let saveRecord = {
            creatorUid: session.uid,
            unionID: msg.unionID,
            userList: [],
            createTime: moment().format('x')
        };
        await commonDao.createData("userBlockModel", saveRecord);
        next(null, {
            code: code.OK
        });
        logger.info(`[addUserBlockRule] operate success`);
    } catch (e) {
        logger.error(`[addUserBlockRule]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//删除同桌功能
Handler.prototype.deleteUserBlockRule = async function (msg, session, next) {

    logger.info(`[deleteUserBlockRule] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.ruleID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[deleteUserBlockRule] ownerUid = ${unionData.ownerUid} isManager = ${userUnionInfoItem.manager} sessionUid = ${session.uid}`);
        //如果不是管理员或者盟主
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //移除一条记录
        await commonDao.deleteData("userBlockModel", {
            'ruleID': msg.ruleID
        });
        next(null, {
            code: code.OK
        });
        logger.info(`[deleteUserBlockRule] operate success`);

    } catch (e) {
        logger.error(`[deleteUserBlockRule]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//修改玩家同桌规则 
Handler.prototype.modifyUserToRule = async function (msg, session, next) {

    logger.info(`[modifyUserToRule] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.userList || !msg.ruleID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[modifyUserToRule] ownerUid = ${unionData.ownerUid} isManager = ${userUnionInfoItem.manager} sessionUid = ${session.uid}`);
        //如果不是管理员或者盟主
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        if (msg.type == 1) {
            //新增
            let uid = msg.userList[0];
            let userData = await userDao.getUserDataByUid(uid);
            if (!userData) {
                next(null, {
                    code: code.INVALID_UERS
                });
                return;
            }
            // 判断是否是盟主
            let userUnionInfoItem = userData.unionInfo.find(function (ele) {
                return ele.unionID === msg.unionID;
            });
            if (userData && userUnionInfoItem) {
                let newUser = {
                    uid: uid,
                    nickname: userData.nickname,
                    avatar: userData.avatar
                };
                await commonDao.findOneAndUpdateEx("userBlockModel", {
                    ruleID: msg.ruleID,
                    unionID: msg.unionID
                }, {
                    $pull: {
                        userList: {
                            uid: uid
                        }
                    }
                });
                await commonDao.findOneAndUpdateEx("userBlockModel", {
                    ruleID: msg.ruleID,
                    unionID: msg.unionID
                }, {
                    $push: {
                        userList: newUser
                    }
                });
                let curReuslt = await commonDao.findOneData('userBlockModel', {
                    ruleID: msg.ruleID,
                    unionID: msg.unionID
                });
                next(null, {
                    code: code.OK,
                    ruleData: curReuslt
                });
                logger.info(`[modifyUserToRule] add limit operate success`);

            } else {
                logger.info(`[modifyUserToRule] add limit operate fail`);
                next(null, {
                    code: code.INVALID_UERS
                });
                return;
            }

        } else {
            //移除
            await commonDao.findOneAndUpdateEx("userBlockModel", {
                ruleID: msg.ruleID,
                unionID: msg.unionID
            }, {
                $pull: {
                    userList: {
                        uid: {
                            $in: msg.userList
                        }
                    }
                }
            });
            let curReuslt = await commonDao.findOneData('userBlockModel', {
                ruleID: msg.ruleID,
                unionID: msg.unionID
            });
            next(null, {
                code: code.OK,
                ruleData: curReuslt
            });
            logger.info(`[modifyUserToRule] remove limit operate success`);
        }
    } catch (e) {
        logger.error(`[modifyUserToRule]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//获取玩家规则列表 
Handler.prototype.userBlockList = async function (msg, session, next) {

    logger.info(`[userBlockList] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }

        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[userBlockList] ownerUid = ${unionData.ownerUid} isManager = ${userUnionInfoItem.manager} sessionUid = ${session.uid}`);
        //如果不是管理员或者合伙人
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        let matchData = {
            'unionID': msg.unionID
        };
        let res = await commonDao.findDataAndCount('userBlockModel', msg.startIndex || 0, msg.count || 20, {
            createTime: 1
        }, matchData);
        next(null, {
            code: code.OK,
            msg: {
                recordArr: res.recordArr,
                totalCount: res.totalCount
            }
        });
        logger.info(`[userBlockList] operate success`);

    } catch (e) {
        logger.error(`[userBlockList]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//获取团队玩家分数统计
Handler.prototype.getUserScore = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //如果不是管理员或者合伙人
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //如果是当天 则先计算当天的数据
        if (msg.dayTime == moment().format('YYYYMMDD')) {
            await userInfoServices.reCountUserScore(msg.unionID, msg.dayTime);
        }
        //如果是管理员 则查询盟主的数据
        let curUid = session.uid;
        if (userUnionInfoItem.manager) {
            curUid = unionData.ownerUid;
        }
        //获取所有下级用户
        let allUserList = await userInfoServices.getUserLowAll(curUid, msg.unionID);
        let matchData = {
            'uid': {
                '$in': allUserList
            },
            'dayTime': msg.dayTime,
            'unionID': msg.unionID
        };
        if (msg.uid) {
            matchData.uid = msg.uid
        }
        let sortArr = {
            score: -1
        };
        if (msg.type == 1) {
            //赢分
            matchData.score = {
                '$gt': 0
            };
        } else if (msg.type == 2) {
            //输分
            matchData.score = {
                '$lt': 0
            };
            sortArr = {
                score: 1
            }
        }
        let res = await commonDao.findDataAndCount('userScoreModel', msg.startIndex || 0, msg.count || 20, sortArr, matchData);
        next(null, {
            code: code.OK,
            msg: {
                recordArr: res.recordArr,
                totalCount: res.totalCount
            }
        });
    } catch (e) {
        logger.error(`[getUserScore]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//查询推荐联盟
Handler.prototype.unionMainList = async function (msg, session, next) {

    try {
        logger.info(`[hall-unionHandler] unionMainList begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        let matchData = {
            isMain: {
                $gt: 0
            }
        };
        logger.error(`unionMainList msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let result = await commonDao.findData("unionModel", matchData, {
            isMain: -1
        }, 0, 6);
        for (let i = 0; i < result.length; i++) {
            let curUnion = result[i];
            let unionID = curUnion.unionID;
            let ownerUid = curUnion.ownerUid;
            let unionUser = await userDao.getUserData({
                'uid': ownerUid
            });
            let curUnionInfo = unionUser.unionInfo.find(function (element) {
                return element.unionID === unionID;
            });
            result[i].inviteID = curUnionInfo && curUnionInfo.inviteID;
        }
        logger.info(`[hall-unionHandler] unionMainList end`);
        next(null, {
            code: code.OK,
            msg: {
                result
            }
        });
    } catch (e) {
        logger.error(`[unionMainList]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//查询玩家分数变化
Handler.prototype.userScoreRecord = async function (msg, session, next) {

    try {
        // logger.info(`[hall-unionHandler] userScoreRecord begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let curUid = msg.uid ? msg.uid : session.uid;
        let dayTime = msg.dayTime ? msg.dayTime : moment().format('YYYYMMDD');
        let startTime = parseInt(moment(dayTime).startOf('d').format('x'));
        let endTime = parseInt(moment(dayTime).endOf('d').format('x'));
        //只提供查询3天内的数据
        let matchData = {
            uid: curUid,
            unionID: msg.unionID,
            createTime: { '$gte': startTime, '$lte': endTime }
        };
        //logger.error(`userScoreRecord msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let result = await commonDao.findDataAndCount("userScoreDetailModel", msg.startIndex || 0, msg.count || 20, {
            createTime: -1
        }, matchData);
        // logger.info(`[hall-unionHandler] userScoreRecord end`);
        next(null, {
            code: code.OK,
            msg: result
        });
    } catch (e) {
        logger.error(`[userScoreRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//获取团队信息汇总
Handler.prototype.getTeamDetail = async function (msg, session, next) {

    try {
        //logger.info(`[hall-unionHandler] getTeamDetail begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //logger.error(`getTeamDetail msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //如果不是管理员或者合伙人
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //userInfoServices.getQuickUserList(msg.unionID, unionData.ownerUid, unionData.ownerUid);
        let memberTotalCount = 0; //所有玩家
        let memberCount = 0; //直属下级
        let outMemberCount = 0; //简介下级
        let spreaderInfo = null; //直属队长
        let rebateRate = userUnionInfoItem.rebateRate || 0; //我的比例
        let totalScore = 0; //团队总积分
        let todayWin = 0; //今日赢分
        let yesterdayWin = 0; //昨日赢分
        let todayRebate = 0; //今日抽水
        let yesterdayRebate = 0; //作日抽水
        let testWin = 0;
        let totalDraw = 0;

        //查找上级用户
        if (userUnionInfoItem.spreaderID) {
            let spreaderUser = await commonDao.findOneData('userModel', {
                uid: userUnionInfoItem.spreaderID
            });
            if (spreaderUser) {
                spreaderInfo = {
                    uid: spreaderUser.uid,
                    nickname: spreaderUser.nickname,
                    avatar: spreaderUser.avatar,
                }
            }
        }
        //如果是管理员 则查询盟主的数据
        let curUid = session.uid;
        if (userUnionInfoItem.manager) {
            curUid = unionData.ownerUid;
        }
        //直属玩家的数据
        let userQuery = {
            unionInfo: {
                $elemMatch: {
                    spreaderID: curUid,
                    unionID: msg.unionID
                }
            }
        };
        // let downUser = await commonDao.findDataAndCount('userModel', 0, 0, { "unionInfo.unionID": 1, "unionInfo.parter": -1 }, userQuery);
        //直属成员数据
        memberCount = await commonDao.getDataCount('userModel', userQuery);
        //获取所有下级用户
        let allUserList = await userInfoServices.getUserLowAll(curUid, msg.unionID);
        //团队总人数
        memberTotalCount = allUserList.length;
        //间接成员数
        outMemberCount = memberTotalCount - memberCount;
        let allUserResult = await userInfoServices.getUserDataTotal(msg.unionID, allUserList);
        todayWin = allUserResult.todayWinTotal; //今日赢分
        yesterdayWin = allUserResult.yesterdayWinTotal; //昨日赢分
        totalScore = allUserResult.totalScore; //团队分数
        totalDraw = allUserResult.totalDraw; //今日局数
        todayRebate = allUserResult.todayTotalRebate; //今日返利
        yesterdayRebate = allUserResult.yesterdayTotalRebate; //昨日返利
        let curUserResult = await userInfoServices.getUserDataTotal(msg.unionID, [curUid]);
        let curUserRebate = curUserResult.todayTotalRebate;
        let curUserYesterdayRebate = curUserResult.yesterdayTotalRebate;
        if (unionData.ownerUid == session.uid || userUnionInfoItem.manager) {
            //获取机器人返利
            let testUser = await commonDao.findData('userModel', {
                'unionInfo.unionID': msg.unionID,
                'isRobot': true
            }, null, 0, 0);
            let testIDList = [];
            for (let i = 0; i < testUser.length; i++) {
                testIDList.push(testUser[i].uid);
            }
            //  let testUserResult = await userInfoServices.getUserDataTotal(msg.unionID, testIDList, false);
            // testWin = testUserResult.todayWinTotal; //今日赢分
        }

        let msgData = {
            testWin,
            curUserYesterdayRebate,
            curUserRebate,
            totalDraw,
            memberTotalCount,
            memberCount,
            outMemberCount,
            spreaderInfo,
            rebateRate,
            totalScore,
            todayWin,
            yesterdayWin,
            todayRebate,
            yesterdayRebate
        };
        //logger.info(`[hall-unionHandler] getTeamDetail end`);
        next(null, {
            code: code.OK,
            msg: msgData
        });
    } catch (e) {
        logger.error(`[getTeamDetail]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//我的返利
Handler.prototype.getMyRebate = async function (msg, session, next) {

    try {
        // logger.info(`[hall-unionHandler] getMyRebate begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // logger.error(`getMyRebate msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //如果不是管理员或者合伙人
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.partner) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        let safeScore = userUnionInfoItem.safeScore;
        let todayRebate = userUnionInfoItem.todayRebate;
        let yesterdayRebate = userUnionInfoItem.yesterdayRebate;
        let curMsg = {
            safeScore,
            todayRebate,
            yesterdayRebate
        }
        if (msg.type != 1) {
            //查询当前返利
            let curUid = session.uid;
            let matchData = {
                'uid': curUid,
                unionID: msg.unionID
            };
            let res = await commonDao.findDataAndCount('userRebateRecordModel', msg.startIndex || 0, msg.count || 20, {
                createTime: -1
            }, matchData);
            curMsg.recordArr = res.recordArr;
            curMsg.recordCount = res.totalCount;
        }
        // logger.info(`[hall-unionHandler] getMyRebate end`);
        next(null, {
            code: code.OK,
            msg: curMsg
        });
    } catch (e) {
        logger.error(`[getMyRebate]` + e.stack);
        next(null, {
            code: 500
        });
    }



};

// 修改合伙人
Handler.prototype.removePartner = async function (msg, session, next) {

    logger.info(`[removePartner] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid || !msg.partnerUid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否是盟主
        let userUnionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        if (!userUnionInfoItem || unionData.ownerUid != session.uid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[removePartner] ownerUid = ${unionData.ownerUid} sessionUid = ${session.uid}`);
        // 查询用户数据
        let partnerData = await userDao.getUserDataByUid(msg.partnerUid);
        if (!partnerData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let parterUnionInfoItem = partnerData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        // 如果不是合伙人
        if (!parterUnionInfoItem || !parterUnionInfoItem.partner) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (ele) { return ele.unionID === msg.unionID; });
        // 玩家不在联盟中
        if (!memberUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        //查询玩家的所有下级
        let userList = await userInfoServices.getUserLowAll(memberUserData.uid, msg.unionID);
        if (userList.includes(msg.partnerUid)) {
            next(null, {
                code: code.TANSFER_LEVEL_LINIT
            });
            return;
        }
        // 更新用户数据
        let newMemberData = await userDao.updateUserData({ uid: msg.memberUid, "unionInfo.unionID": msg.unionID }, { "unionInfo.$.spreaderID": msg.partnerUid });

        //保存记录-修改队长
        let doneUid = newMemberData.uid;
        let doneAvatar = newMemberData.avatar;
        let doneNickname = newMemberData.nickname;
        let uid = userData.uid;
        let avatar = userData.avatar;
        let nickname = userData.nickname;

        await commonDao.createData('userDelModel', {
            type: 6,
            doneUid,
            doneAvatar,
            doneNickname,
            uid,
            avatar,
            nickname,
            score: 0,
            unionID: unionData.unionID,
            createTime: Date.now()
        });


        logger.info(`[removePartner] operate success`);
        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[removePartner]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

// 创建联盟
Handler.prototype.createUnion = async function (msg, session, next) {

    logger.info(`[createUnion] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {

        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }

        if (!userList[session.uid]) {
            userList[session.uid] = moment();
        } else {
            if (moment().diff(userList[session.uid], 's') < 5) {
                next(null, { code: code.REQUEST_DATA_ERR });
                return;
            }
        }

        // 判断参数是否有效
        let unionName = msg.unionName;
        if (!unionName || unionName.length > 20) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        // 查询是否有创建联盟的资格
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData.isAgent) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }

        //判断是否达到钻石最低要求
        let createGold = parseInt(this.app.get('config') && this.app.get('config')['createUnionGold']) || 100;
        if (userData.gold < createGold) {
            next(null, { code: code.NOT_ENOUGH_GOLD });
            return;
        }

        // 判断是否达到最大联盟数量
        // let unionConfig = JSON.parse((this.app.get('config') && this.app.get('config')['unionConfig']) || '{}');
        // let userMaxUnionCount = unionConfig['userMaxUnionCount'] || 20;
        // if (userData.unionInfo.length >= userMaxUnionCount) {
        //     next(null, {
        //         code: code.REQUEST_DATA_ERROR
        //     });
        //     return;
        // }
        // 判断是否已经创建过牌友圈，如果已经创建过，则无法重复创建
        // let union = await commonDao.findOneData('unionModel', { unionName: unionName });
        // if (!!union) {
        //     next(null, { code: code.ALREADY_CREATED_UNION });
        //     return;
        // }

        // 创建联盟
        let saveUnionData = {
            ownerUid: session.uid,
            ownerNickname: userData.nickname,
            ownerAvatar: userData.avatar,
            unionName: unionName,
            unionSkinId: msg.unionSkinId,
            unionType: msg.unionType || 1, //0 比赛场  1普通场
            unionGameType: msg.unionGameType || 301, //游戏类型
            ownerPhone: msg.ownerPhone || null,
            ownerWeChat: msg.ownerWeChat || null,
            curMember: 1,
            createTime: Date.now()
        };
        let unionData = await commonDao.createData("unionModel", saveUnionData);
        if (!unionData) {
            next(null, {
                code: code.SQL_ERROR
            });
            return;
        }
        // 更新用户信息
        let unionInfo = {
            unionID: unionData.unionID,
            partner: true,
            rebateRate: 1,
            ticketRate: 1,
            sortType: 5,
            fixScoreRate: 1,
            joinTime: Date.now()
        };

        let uniqueIDData = await commonDao.findOneAndUpdateEx("uniqueIDModel", { key: 1 }, { $inc: { unionInviteID: 7 } }, { new: true, upsert: true });
        unionInfo.inviteID = uniqueIDData.unionInviteID;
        unionInfo.unionInviteID = uniqueIDData.unionInviteID;
        let newUserData = await userDao.updateUserDataByUid(session.uid, { $addToSet: { unionInfo: unionInfo } });
        let userUnions = await userInfoServices.getUserUnions(newUserData);

        //更新联盟邀请ID
        await commonDao.updateData('unionModel', { unionID: unionData.unionID }, { unionInviteID: uniqueIDData.unionInviteID });

        next(null, {
            code: code.OK,
            updateUserData: {
                unionInfo: newUserData.unionInfo,
                userUnions: userUnions,
            },
            msg: {
                unionID: unionData.unionID
            }
        });
        logger.info(`[createUnion] operate success`);
    } catch (e) {
        logger.error(`[createUnion]` + e.stack);
        next(null, { code: 500 });
    }

};

// 申请退出申请
Handler.prototype.askJoinUnion = async function (msg, session, next) {

    logger.info(`[askJoinUnion] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }

        //退出联盟
        if (msg.type == 2) {
            // 联盟信息
            let unionData = await commonDao.findOneData('unionModel', { unionID: msg.unionID });
            if (!unionData) {
                next(null, { code: code.UNION_NOT_EXIST });
                return;
            }

            // 玩家信息
            let userData = await userDao.getUserData({ uid: session.uid });
            if (!userData.unionInfo.find(item => item.unionID == msg.unionID)) {
                next(null, { code: code.NOT_IN_UNION });
                return;
            }

            //判断是否重复申请
            let exitRequestList = unionData.exitRequestList;
            if (exitRequestList.find(item => item.uid == session.uid)) {
                next(null, { code: code.CAN_NOT_REPEAT_APPLICATION });
                return;
            }
            // 更新联盟数据
            await await commonDao.updateData('unionModel', {
                unionID: msg.unionID
            }, {
                $push: {
                    exitRequestList: {
                        uid: userData.uid,
                        nickname: userData.nickname,
                        avatar: userData.avatar,
                        createTime: Date.now()
                    }
                }
            });
            logger.info(`[askJoinUnion] operate success pengding`);
            next(null, { code: code.OK });

        } else {

            let inviteID = parseInt(msg.inviteID || "0");
            if (!inviteID) {
                next(null, { code: code.REQUEST_DATA_ERROR });
                return;
            }
            // 联盟信息
            let unionData = await commonDao.findOneData('unionModel', { unionInviteID: inviteID });
            if (!unionData) {
                next(null, { code: code.UNION_NOT_EXIST });
                return;
            }
            // 检查邀请权限
            if (unionData.inviteLimit) {
                next(null, { code: code.CAN_NOT_JOIN_UNION });
                return;
            }
            // 检查邀请权限
            if (!!unionData.forbidInvite && session.uid !== unionData.ownerUid) {
                next(null, { code: code.FORBID_INVITE_SCORE });
                return;
            }
            // 玩家信息
            let userData = await userDao.getUserData({ uid: session.uid });
            if (userData.unionInfo.find(item => item.unionID == inviteID)) {
                next(null, { code: code.ALREADY_IN_UNION });
                return;
            }
            //需要邀请
            let joinRequestList = unionData.joinRequestList;
            if (joinRequestList.find(item => item.uid == session.uid)) {
                next(null, { code: code.CAN_NOT_REPEAT_APPLICATION });
                return;
            }
            // 更新联盟数据
            await await commonDao.updateData('unionModel', { unionID: unionData.unionID }, {
                $push: {
                    joinRequestList: {
                        inviteID: inviteID,
                        spreaderID: unionData.ownerUid,
                        uid: userData.uid,
                        nickname: userData.nickname,
                        avatar: userData.avatar,
                        createTime: Date.now()
                    }
                }
            });
            logger.info(`[askJoinUnion] operate success pengding`);
            next(null, { code: code.OK });
        }

    } catch (e) {
        logger.error(`[askjoinUnion]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//查看审核列表
Handler.prototype.askJoinUnionList = async function (msg, session, next) {

    //logger.info(`[askJoinUnionList] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', { unionID: msg.unionID });
        if (!unionData) {
            next(null, { code: code.UNION_NOT_EXIST });
            return;
        }
        // 玩家信息
        let userData = await userDao.getUserData({ uid: session.uid });
        let unionInfoItem = userData.unionInfo.find(item => item.unionID == msg.unionID);
        let list = [];
        if (unionInfoItem && (unionData.ownerUid == session.uid || unionInfoItem.manager)) {
            let joinRequestList = unionData.joinRequestList;
            let exitRequestList = unionData.exitRequestList;
            list = msg.type == 2 ? exitRequestList : joinRequestList;
        }
        let recordCount = list.length;
        if (msg.memberUid) {
            list = list.filter(item => item.uid == msg.memberUid);
        } else {
            let startIndex = msg.startIndex || 0;
            let count = msg.count || 10;
            list = list.slice(startIndex, count);
        }
        next(null, { code: code.OK, msg: { recordCount, recordArr: list } });

    } catch (e) {
        logger.error(`[askJoinUnionList]` + e.stack);
        next(null, { code: 500 });
    }

};

//审核
Handler.prototype.joinUnionApprove = async function (msg, session, next) {

    logger.info(`[joinUnionApprove] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid || !msg.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        //退出
        if (msg.type == 2) {

            let unionData = await commonDao.findOneData('unionModel', { unionID: msg.unionID });
            if (!unionData) {
                next(null, { code: code.UNION_NOT_EXIST });
                return;
            }
            let userData = await userDao.getUserData({ uid: session.uid });
            let unionInfoItem = userData.unionInfo.find(item => item.unionID == msg.unionID);
            if (unionInfoItem && (unionData.ownerUid == session.uid || unionInfoItem.manager)) {
                // 更新联盟数据
                await commonDao.updateData('unionModel', { unionID: msg.unionID }, { $pull: { exitRequestList: { uid: msg.uid } } });
                //审核通过
                if (msg.approveType) {

                    //更新联盟数据
                    await commonDao.updateData('unionModel', { unionID: msg.unionID }, { $inc: { curMember: -1 } });
                    // 删除联盟数据
                    let newMemberData = await userDao.updateUserDataByUid(msg.uid, { $pull: { unionInfo: { unionID: msg.unionID } } });
                    if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                        unionInfo: newMemberData.unionInfo
                    }).catch(e => {
                        logger.error(e.stack)
                    });
                }
                next(null, { code: code.OK });

            } else {
                next(null, { code: code.PERMISSION_NOT_ENOUGH });
                return;
            }

        }
        else {

            let inviteID = msg.inviteID;
            // 联盟信息
            let unionData = await commonDao.findOneData('unionModel', { unionInviteID: inviteID });
            if (!unionData) {
                next(null, { code: code.UNION_NOT_EXIST });
                return;
            }

            let userData = await userDao.getUserData({ uid: session.uid });
            let inviteUnionInfo = userData.unionInfo.find(item => item.unionID == unionData.unionID);

            // 检查邀请权限
            if (!!unionData.forbidInvite && (session.uid !== unionData.ownerUid || !inviteUnionInfo.manager)) {
                next(null, { code: code.FORBID_INVITE_SCORE });
                return;
            }
            // 更新联盟数据
            await commonDao.updateData('unionModel', { unionID: unionData.unionID }, { $pull: { joinRequestList: { inviteID: inviteID, uid: msg.uid } } });
            //审核通过
            if (msg.approveType) {

                let maxUser = parseInt(this.app.get('config') && this.app.get('config')['maxUnionMemberCount']) || 200;
                if (unionData.curMember >= maxUser) {
                    next(null, { code: code.REQUEST_DATA_ERROR });
                    logger.info(`[joinUnionApprove] fail user max  = ${maxUser} curMember = ${unionData.curMember} `);
                    return;
                }

                await commonDao.updateData('unionModel', { unionID: unionData.unionID }, { $inc: { curMember: 1 } });
                // 修改用户数据
                let addUnionInfo = {
                    spreaderID: unionData.ownerUid,
                    unionID: unionData.unionID,
                    joinTime: Date.now()
                };
                let uniqueIDData = await commonDao.findOneAndUpdateEx("uniqueIDModel", { key: 1 }, { $inc: { unionInviteID: 7 } }, { new: true, upsert: true });
                addUnionInfo.inviteID = uniqueIDData.unionInviteID;
                let newMemberData = await userDao.updateUserDataByUid(msg.uid, { $push: { unionInfo: addUnionInfo } });
                if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                    unionInfo: newMemberData.unionInfo
                }).catch(e => {
                    logger.error(e.stack)
                });


                let doneUid = newMemberData.uid;
                let doneAvatar = newMemberData.avatar;
                let doneNickname = newMemberData.nickname;
                let uid = userData.uid;
                let avatar = userData.avatar;
                let nickname = userData.nickname;

                await commonDao.createData('userDelModel', {
                    type: 0,
                    doneUid,
                    doneAvatar,
                    doneNickname,
                    uid,
                    avatar,
                    nickname,
                    score: 0,
                    unionID: unionData.unionID,
                    createTime: Date.now()
                });

                logger.info(`[joinUnionApprove] operate success approved`);
            }
            next(null, {
                code: code.OK
            });
        }

    } catch (e) {
        logger.error(`[joinUnionApprove]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

// 加入联盟--不能加入
Handler.prototype.joinUnion = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        let inviteID = parseInt(msg.inviteID || "0");
        if (!inviteID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询邀请玩家信息
        let inviteUserData = await userDao.getUserData({
            "unionInfo.inviteID": inviteID
        });
        if (!inviteUserData) {
            next(null, {
                code: code.INVITE_ID_ERROR
            });
            return;
        }
        let inviteUnionInfo = inviteUserData.unionInfo.find(function (ele) {
            return ele.inviteID === inviteID;
        });
        if (!inviteUnionInfo) {
            next(null, {
                code: code.INVITE_ID_ERROR
            });
            return;
        }
        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: inviteUnionInfo.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 检查邀请权限
        if (!!unionData.forbidInvite && session.uid !== unionData.ownerUid) {
            next(null, {
                code: code.FORBID_INVITE_SCORE
            });
            return;
        }
        let userData = await userDao.getUserData({
            uid: session.uid
        });
        for (let i = 0; i < userData.unionInfo.length; ++i) {
            let info = userData.unionInfo[i];
            if (info.unionID === inviteUnionInfo.unionID) {
                next(null, {
                    code: code.ALREADY_IN_UNION
                });
                return;
            }
        }
        // 更新联盟数据
        await await commonDao.updateData('unionModel', {
            unionID: inviteUnionInfo.unionID
        }, {
            $inc: {
                curMember: 1
            }
        });
        // 修改用户数据
        let addUnionInfo = {
            spreaderID: inviteUserData.uid,
            unionID: inviteUnionInfo.unionID,
            joinTime: Date.now()
        };
        let uniqueIDData = await commonDao.findOneAndUpdateEx("uniqueIDModel", {
            key: 1
        }, {
            $inc: {
                unionInviteID: 7
            }
        }, {
            new: true,
            upsert: true
        });
        addUnionInfo.inviteID = uniqueIDData.unionInviteID;
        let newUserData = await userDao.updateUserDataByUid(session.uid, {
            $push: {
                unionInfo: addUnionInfo
            }
        });

        let userUnions = userInfoServices.getUserUnions(newUserData);

        next(null, {
            code: code.OK,
            updateUserData: {
                userUnions: userUnions,
                unionInfo: newUserData.unionInfo
            },
            msg: {
                unionID: inviteUnionInfo.unionID
            }
        });
    } catch (e) {
        logger.error(`[joinUnion]` + e.stack);
        next(null, {
            code: 500
        });
    }

};


// 退出联盟
Handler.prototype.exitUnion = async function (msg, session, next) {

    logger.info(`[exitUnion] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData("unionModel", {
            unionID: msg.unionID
        });
        if (!unionData) {
            let newUserData = await userDao.updateUserDataByUid(session.uid, {
                $push: {
                    unionInfo: {
                        unionID: msg.unionID
                    }
                }
            });
            next(null, {
                code: code.OK,
                updateUserData: {
                    unionInfo: newUserData.unionInfo
                }
            });
            return;
        }
        // 盟主不能退出联盟，必须将联盟转移给他认之后
        if (unionData.ownerUid === session.uid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserData({
            uid: session.uid,
            "unionInfo.unionID": msg.unionID
        });
        if (!userData) {
            next(null, {
                code: code.OK
            });
            return;
        }
        // 查询俱乐部信息
        let unionInfoItem = null;
        for (let i = 0; i < userData.unionInfo.length; ++i) {
            if (userData.unionInfo[i].unionID === msg.unionID) {
                unionInfoItem = userData.unionInfo[i];
                break;
            }
        }
        if (!unionInfoItem) {
            next(null, {
                code: code.OK
            });
            return;
        }
        if (unionInfoItem.score > 1) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 删除联盟数据
        let newUserData = await userDao.updateUserDataByUid(session.uid, {
            $pull: {
                unionInfo: {
                    unionID: msg.unionID
                }
            }
        });
        // 将下级用户转移给上级玩家
        await commonDao.updateAllData("userModel", {
            unionInfo: {
                $elemMatch: {
                    spreaderID: session.uid,
                    unionID: msg.unionID
                }
            }
        }, {
            "unionInfo.$.spreaderID": unionInfoItem.spreaderID
        });
        // 更新俱乐部人数
        commonDao.updateData("unionModel", {
            unionID: msg.unionID
        }, {
            $inc: {
                curMember: -1
            }
        }).catch(e => {
            logger.error(e.stack)
        });
        next(null, {
            code: code.OK,
            updateUserData: {
                unionInfo: newUserData.unionInfo
            }
        });
        logger.info(`[exitUnion] operate success `);
    } catch (e) {
        logger.error(`[exitUnion]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

// 获取用户联盟列表
Handler.prototype.getUserUnionList = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 获取用户信息
        let userData = await userDao.getUserDataByUid(session.uid);
        let recordArr = await userInfoServices.getUserUnions(userData);
        next(null, {
            code: code.OK,
            updateUserData: {
                userUnions: recordArr,
                unionInfo: userData.unionInfo
            },
            msg: {
                recordArr: recordArr
            }
        });
    } catch (e) {
        logger.error(`[getUserUnionList]` + e.stack);
        next(null, {
            code: 500
        });
    }


};
// 获取所有在线成员列表
Handler.prototype.getAllOnLineList = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        logger.error(`getAllOnLineList msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let res = await commonDao.findDataAndCount('userModel', msg.startIndex || 0, msg.count || 20, {
            frontendId: 1,
            roomID: 1
        }, msg.matchData);
        let recordCount = await commonDao.getDataCount('userModel', msg.matchData);
        let recordArr = [];
        //表示我的玩家和所有成员
        for (let i = 0; i < res.recordArr.length; ++i) {
            let userData = res.recordArr[i];
            let unionInfoItem = userData.unionInfo.find(function (ele) {
                return ele.unionID === msg.unionID;
            });
            let spreaderInfo = null;
            if (unionInfoItem.spreaderID) {
                let spreaderUser = await commonDao.findOneData('userModel', {
                    uid: unionInfoItem.spreaderID
                });
                if (spreaderUser) {
                    spreaderInfo = {
                        uid: spreaderUser.uid,
                        nickname: utils.getNickName(spreaderUser.nickname),
                        avatar: spreaderUser.avatar,
                    }
                }
            }
            if (userData.frontendId == '') continue;
            recordArr.push({
                uid: userData.uid,
                avatar: userData.avatar,
                nickname: utils.getNickName(userData.nickname),
                lastLoginTime: userData.lastLoginTime,
                roomID: userData.roomID,
                frontendId: userData.frontendId,
            })
        }
        next(null, {
            code: code.OK,
            msg: {
                recordArr,
                recordCount
            }
        });
    } catch (e) {
        logger.error(`[getAllOnLineList]` + e.stack);
        next(null, {
            code: 500
        });
    }

}

//获取玩家成员列表
Handler.prototype.getUnionMember = async function (msg, session, next) {

    logger.info(`[getUnionMember] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.unionID) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        // 查询用户数据
        let curUid = msg.uid ? msg.uid : session.uid;
        let userData = await userDao.getUserDataByUid(curUid);
        if (!userData) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', { unionID: msg.unionID });
        if (!unionData) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }

        let matchData = { unionInfo: { $elemMatch: { spreaderID: userData.uid, unionID: msg.unionID } } };
        let userQuery = { 'unionInfo.spreaderID': userData.uid, 'unionInfo.unionID': msg.unionID };
        let unionInfo = userData.unionInfo.find(item => item.unionID == msg.unionID);
        if (unionInfo.manager || unionData.ownerUid == userData.uid) {
            matchData = { unionInfo: { $elemMatch: { unionID: msg.unionID } } };
            userQuery = { 'unionInfo.unionID': msg.unionID };
        }
        if (msg.searchUid) {
            matchData['uid'] = msg.searchUid;
            userQuery['uid'] = msg.searchUid;
        }
        let res = await commonDao.findDataAndCount('userModel', msg.startIndex || 0, msg.count || 20, { isRobot: 1, 'unionInfo.sortType': -1 }, matchData);

        // let execData = [{ '$unwind': "$unionInfo" }, { '$match': userQuery }, { '$sort': { 'unionInfo.sortType': -1 } }, { '$skip': msg.startIndex || 0 }, { '$limit': msg.count || 10 }];
        // let result = await commonDao.getStatisticsInfo('userModel', execData);

        // res.recordArr = result;

        let recordArr = [];
        let recordCount = res.totalCount;
        for (let i = 0; i < res.recordArr.length; ++i) {
            let userData = res.recordArr[i];
            let unionInfoItem = userData.unionInfo.find(item => item.unionID == msg.unionID);
            //let unionInfoItem = userData.unionInfo;
            let spreaderInfo = null;
            if (unionInfoItem.spreaderID) {
                let spreaderUser = await commonDao.findOneData('userModel', { uid: unionInfoItem.spreaderID });
                if (spreaderUser) {
                    spreaderInfo = {
                        uid: spreaderUser.uid,
                        nickname: utils.getNickName(spreaderUser.nickname),
                        avatar: spreaderUser.avatar,
                    }
                }
            }
            recordArr.push({
                spreaderInfo: spreaderInfo,
                uid: userData.uid,
                nickname: utils.getNickName(userData.nickname),
                lastLoginTime: userData.lastLoginTime,
                avatar: userData.avatar,
                isRobot: userData.isRobot,
                frontendId: userData.frontendId,
                roomID: userData.roomID,
                spreaderID: unionInfoItem.spreaderID,
                score: unionInfoItem.score,
                saveScore: unionInfoItem.saveScore,
                safeScore: unionInfoItem.safeScore,
                prohibitGame: unionInfoItem.prohibitGame,
                partner: unionInfoItem.partner,
                manager: unionInfoItem.manager,
            })
        }
        next(null, {
            code: code.OK,
            msg: { recordArr, recordCount }
        });
    }
    catch (e) {
        logger.error(`[getUnionMember]` + e.stack);
        next(null, {
            code: 500
        });
    }

}

//获取队长列表
Handler.prototype.getUnionParter = async function (msg, session, next) {

    logger.info(`[getUnionParter] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {

        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        if (!msg.unionID) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        // 查询用户数据
        let curUid = msg.uid ? msg.uid : session.uid;
        let userData = await userDao.getUserDataByUid(curUid);
        if (!userData) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', { unionID: msg.unionID });
        if (!unionData) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        //不是队长
        let unionInfo = userData.unionInfo.find(item => item.unionID == msg.unionID);
        if (!unionInfo.partner && !unionInfo.manager) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }

        let matchData = { unionInfo: { $elemMatch: { partner: true, spreaderID: userData.uid, unionID: msg.unionID } } };

        if (unionInfo.manager || unionData.ownerUid == userData.uid) {
            matchData = { unionInfo: { $elemMatch: { partner: true, spreaderID: unionData.ownerUid, unionID: msg.unionID } } };
            matchData = { '$or': [matchData, { 'uid': unionData.ownerUid }] };
        } else {
            matchData = { '$or': [matchData, { 'uid': userData.uid }] };
        }
        if (msg.searchUid) {
            matchData['uid'] = msg.searchUid;
        }
        let res = await commonDao.findDataAndCount('userModel', msg.startIndex || 0, msg.count || 20, { 'isRobot': 1, 'unionInfo.sortType': -1 }, matchData);
        let recordArr = [];
        let recordCount = res.totalCount;

        let spreaderInfo = {
            uid: userData.uid,
            nickname: utils.getNickName(userData.nickname),
            avatar: userData.avatar,
        }

        for (let i = 0; i < res.recordArr.length; ++i) {
            let userData = res.recordArr[i];
            let lowUserList = await userInfoServices.getUserLowAll(userData.uid, msg.unionID);
            let unionInfoItem = userData.unionInfo.find(item => item.unionID == msg.unionID);
            let score = 0;
            let totalScore = 0;
            let rebateScore = 0;
            let limitScore = unionInfoItem.limitScore;
            if (msg.teamData) {
                // score = parseFloat((parseFloat(unionInfoItem.score) + parseFloat(unionInfoItem.saveScore) + parseFloat(unionInfoItem.safeScore)).toFixed(2));
                score = parseFloat(unionInfoItem.score);
                let allDetail = await userInfoServices.getAllUserDetail(lowUserList, msg.unionID);
                totalScore = allDetail.totalScore;
                rebateScore = allDetail.rebateScore;
            }
            recordArr.push({
                spreaderInfo: spreaderInfo,
                limitScore: limitScore,
                uid: userData.uid,
                nickname: utils.getNickName(userData.nickname),
                lastLoginTime: userData.lastLoginTime,
                avatar: userData.avatar,
                isRobot: userData.isRobot,
                partner: unionInfoItem.partner,
                manager: unionInfoItem.manager,
                frontendId: userData.frontendId,
                roomID: userData.roomID,
                playerCount: lowUserList.length,
                score: score,
                rebateScore: rebateScore,
                totalScore: totalScore
            })
        }
        next(null, {
            code: code.OK,
            msg: { recordArr, recordCount }
        });
    }
    catch (e) {
        logger.error(`[getUnionParter]` + e.stack);
        next(null, {
            code: 500
        });
    }


}

//获取管理里面的我的队长
Handler.prototype.getMyParter = async function (msg, session, next) {


}

// 获取成员列表
Handler.prototype.getMemberList = async function (msg, session, next) {

    logger.info(`[getMemberList] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let res = await commonDao.findDataAndCount('userModel', msg.startIndex || 0, msg.count || 20, {
            'unionInfo.joinTime': 1
        }, msg.matchData);
        let recordCount = res.totalCount;
        let recordArr = [];
        //表示我的玩家和所有成员
        if (msg.isMyMember) {

            for (let i = 0; i < res.recordArr.length; ++i) {
                let userData = res.recordArr[i];
                let unionInfoItem = userData.unionInfo.find(function (ele) {
                    return ele.unionID === msg.unionID;
                });

                let spreaderInfo = null;
                if (unionInfoItem.spreaderID) {
                    let spreaderUser = await commonDao.findOneData('userModel', {
                        uid: unionInfoItem.spreaderID
                    });
                    if (spreaderUser) {
                        spreaderInfo = {
                            uid: spreaderUser.uid,
                            nickname: utils.getNickName(spreaderUser.nickname),
                            avatar: spreaderUser.avatar,
                        }
                    }
                }
                //统计需要减去自己的分数
                recordArr.push({
                    spreaderInfo: spreaderInfo,
                    uid: userData.uid,
                    nickname: utils.getNickName(userData.nickname),
                    lastLoginTime: userData.lastLoginTime,
                    avatar: userData.avatar,
                    isRobot: userData.isRobot,
                    frontendId: userData.frontendId,
                    roomID: userData.roomID,
                    spreaderID: unionInfoItem.spreaderID,
                    score: unionInfoItem.score,
                    safeScore: unionInfoItem.safeScore,
                    prohibitGame: unionInfoItem.prohibitGame,
                    partner: unionInfoItem.partner,
                    manager: unionInfoItem.manager,
                    targetScore: unionInfoItem.targetScore,
                    floatScore: unionInfoItem.floatScore,
                    yesterdayDraw: unionInfoItem.yesterdayDraw,
                    yesterdayBigWinDraw: unionInfoItem.yesterdayBigWinDraw,
                    yesterdayRebate: unionInfoItem.yesterdayRebate,
                    todayRebate: unionInfoItem.todayRebate,

                    memberYesterdayDraw: unionInfoItem.memberYesterdayDraw,
                    memberYesterdayBigWinDraw: unionInfoItem.memberYesterdayBigWinDraw,
                    yesterdayProvideRebate: unionInfoItem.yesterdayProvideRebate,
                    todayProvideRebate: unionInfoItem.todayProvideRebate,
                    todayWin: unionInfoItem.todayWin,
                    yesterdayWin: unionInfoItem.yesterdayWin,
                    totalDraw: unionInfoItem.totalDraw,
                    limitScore: unionInfoItem.limitScore,
                    rebateRate: unionInfoItem.rebateRate,
                    fixScoreRate: unionInfoItem.fixScoreRate,
                    ticketRate: unionInfoItem.ticketRate,
                    // partner: unionInfoItem.partner,
                    // manager: unionInfoItem.manager

                })
            }
            next(null, {
                code: code.OK,
                msg: {
                    recordArr,
                    recordCount
                }
            });

        } else {
            //统计自己战队所有人的分数人数及分数
            // let totalQuery = { unionInfo: { $elemMatch: { spreaderID: session.uid, unionID: msg.unionID } } };
            //如果是合伙人先新增一条自己的分数
            let curUid = session.uid;
            if (msg.partnerPage) {

                let myUser = await commonDao.findOneData('userModel', {
                    'uid': session.uid
                });
                //如果当前用户还是管理员 则不加入自己
                let unionInfoItem = myUser.unionInfo.find(function (ele) {
                    return ele.unionID === msg.unionID;
                });
                if (unionInfoItem && !unionInfoItem.manager) {
                    res.recordArr.unshift(myUser);
                }

                // 查询联盟数据
                let unionData = await commonDao.findOneData('unionModel', {
                    unionID: msg.unionID
                });
                if (unionData) {
                    //不是盟主的管理员
                    if (unionData.ownerUid != session.uid && unionInfoItem.manager) {
                        myUser = await commonDao.findOneData('userModel', {
                            'uid': unionData.ownerUid
                        });
                        res.recordArr.unshift(myUser);
                        curUid = unionData.ownerUid;
                    }
                }
            }

            let unionALlUser = await userInfoServices.getUnionAllUser(msg.unionID);
            for (let i = 0; i < res.recordArr.length; ++i) {
                let userData = res.recordArr[i];
                let score = 0;
                let safeScore = 0;
                let saveScore = 0;
                let unionInfoItem = userData.unionInfo.find(function (ele) {
                    return ele.unionID === msg.unionID;
                });
                for (let j = 0; j < userData.unionInfo.length; ++j) {
                    if (userData.unionInfo[j].unionID === msg.unionID) {
                        score = userData.unionInfo[j].score;
                        safeScore = userData.unionInfo[j].safeScore;
                        saveScore = userData.unionInfo[j].saveScore || 0;
                    }
                }

                let userList = await userInfoServices.getUserLowAll(userData.uid, msg.unionID, unionALlUser);
                //查询所有玩家的总输赢
                let todayTime = moment().format('YYYYMMDD');
                let yesterdayTime = moment().add(-1, 'd').format('YYYYMMDD');
                let todayDetail = await userInfoServices.getTodayUserScore(msg.unionID, userList, todayTime);
                let yesterdayDetail = await userInfoServices.getTodayUserScore(msg.unionID, userList, yesterdayTime);
                let ownIndex = userList.findIndex(item => item == userData.uid);
                // userList.splice(ownIndex, 1);
                let allUserResult = await userInfoServices.getUserDataTotal(msg.unionID, userList, false);
                let totalCount = allUserResult.totalCount;
                //   let totalScore = allUserResult.totalScore + unionInfoItem.score + unionInfoItem.safeScore + (unionInfoItem.saveScore || 0);
                let totalScore = allUserResult.totalScore;
                let spreaderInfo = null;
                if (unionInfoItem.spreaderID) {
                    let spreaderUser = await commonDao.findOneData('userModel', {
                        uid: unionInfoItem.spreaderID
                    });
                    if (spreaderUser) {
                        spreaderInfo = {
                            uid: spreaderUser.uid,
                            nickname: utils.getNickName(spreaderUser.nickname),
                            avatar: spreaderUser.avatar,
                        }
                    }
                }

                //统计需要减去自己的分数
                recordArr.push({

                    // todayWin: allUserResult.todayWinTotal,
                    // todayDraw: allUserResult.todayDrawTotal,
                    //  yesterdayDrawTotal: allUserResult.yesterdayDrawTotal,
                    //  yesterdayWin: allUserResult.yesterdayTotalWin,
                    todayWin: todayDetail.todayWin,
                    todayDraw: todayDetail.todayDraw,
                    yesterdayDrawTotal: yesterdayDetail.todayDraw,
                    yesterdayWin: yesterdayDetail.todayWin,
                    spreaderInfo: spreaderInfo,
                    uid: userData.uid,
                    playerCount: totalCount,
                    totalScore: totalScore,
                    nickname: utils.getNickName(userData.nickname),
                    lastLoginTime: userData.lastLoginTime,
                    avatar: userData.avatar,
                    frontendId: userData.frontendId,
                    roomID: userData.roomID,
                    spreaderID: unionInfoItem.spreaderID,
                    score: unionInfoItem.score,
                    saveScore: (unionInfoItem.saveScore || 0),
                    safeScore: unionInfoItem.safeScore,
                    prohibitGame: unionInfoItem.prohibitGame,

                    yesterdayDraw: unionInfoItem.yesterdayDraw,
                    yesterdayBigWinDraw: unionInfoItem.yesterdayBigWinDraw,
                    yesterdayRebate: unionInfoItem.yesterdayRebate,
                    todayRebate: unionInfoItem.todayRebate,

                    memberYesterdayDraw: unionInfoItem.memberYesterdayDraw,
                    memberYesterdayBigWinDraw: unionInfoItem.memberYesterdayBigWinDraw,
                    yesterdayProvideRebate: unionInfoItem.yesterdayProvideRebate,


                    totalDraw: unionInfoItem.totalDraw,
                    limitScore: unionInfoItem.limitScore,
                    rebateRate: unionInfoItem.rebateRate,
                    fixScoreRate: unionInfoItem.fixScoreRate,
                    ticketRate: unionInfoItem.ticketRate,
                    partner: unionInfoItem.partner,
                    targetScore: unionInfoItem.targetScore,
                    floatScore: unionInfoItem.floatScore,

                })
            }
            next(null, {
                code: code.OK,
                msg: {
                    recordArr,
                    recordCount,
                    totalCount: recordCount
                }
            });
        }

    } catch (e) {
        logger.error(`[getMemberList]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//玩家统计
Handler.prototype.getMemberStatisticsInfo = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        logger.error(`getMemberStatisticsInfo msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let groupData = {
            _id: null,
            yesterdayTotalDraw: {
                $sum: "$unionInfo.yesterdayDraw"
            },
            yesterdayTotalProvideRebate: {
                $sum: "$unionInfo.yesterdayProvideRebate"
            },
            totalCount: {
                $sum: 1
            }
        };
        let execData = [{
            $unwind: "$unionInfo"
        },
        {
            $match: msg.matchData
        },
        {
            $group: groupData
        }
        ];
        let result = await commonDao.getStatisticsInfo('userModel', execData);
        let yesterdayTotalDraw = 0;
        let yesterdayTotalProvideRebate = 0;
        let totalCount = 0;
        if (result.length > 0) {
            yesterdayTotalDraw = result[0].yesterdayTotalDraw || 0;
            yesterdayTotalProvideRebate = result[0].yesterdayTotalProvideRebate || 0;
            totalCount = result[0].totalCount;
        }
        next(null, {
            code: code.OK,
            msg: {
                yesterdayTotalDraw: yesterdayTotalDraw,
                totalCount: totalCount,
                yesterdayTotalProvideRebate: yesterdayTotalProvideRebate
            }
        });
    } catch (e) {
        logger.error(`[getMemberStatisticsInfo]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

// 获取积分列表
Handler.prototype.getMemberScoreList = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let res = await commonDao.findDataAndCount('userModel', msg.startIndex || 0, msg.count || 20, {
            "unionInfo.joinTime": 1,
        }, msg.matchData);

        let recordCount = await commonDao.getDataCount('userModel', msg.matchData);

        let recordArr = [];

        for (let i = 0; i < res.recordArr.length; ++i) {
            let userData = res.recordArr[i];
            let unionInfoItem = userData.unionInfo.find(function (ele) {
                return ele.unionID === msg.unionID;
            });
            recordArr.push({
                uid: userData.uid,
                isRobot: userData.isRobot,
                nickname: utils.getNickName(userData.nickname),
                avatar: userData.avatar,
                score: unionInfoItem.score,
                safeScore: unionInfoItem.safeScore,
                saveScore: unionInfoItem.saveScore || 0,
                spreaderID: unionInfoItem.spreaderID,
            });
        }
        // 判断玩家数据是否被锁定
        let curUser = await userDao.getUserDataByUid(session.uid);
        if (!curUser) {
            next(null, {
                code: code.USER_DATA_LOCKED
            });
            return;
        }
        let unionInfoItem = curUser.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });

        if (!unionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        let userDataList = null;
        if (unionData.ownerUid === session.uid || unionInfoItem.manager) {
            //盟主
            userDataList = await commonDao.findDataAndCount('userModel', 0, 0, {
                "unionInfo.score": -1
            }, msg.matchData);
        } else {
            let userQuery = {
                unionInfo: {
                    $elemMatch: {
                        unionID: msg.unionID,
                        spreaderID: session.uid
                    }
                }
            };
            userDataList = await commonDao.findDataAndCount('userModel', 0, 0, {
                "unionInfo.score": -1
            }, userQuery);
        }
        let totalCount = userDataList.recordArr.length;
        let totalScore = 0;
        for (let i = 0; i < userDataList.recordArr.length; ++i) {
            let userData = userDataList.recordArr[i];
            let unionInfoItem = userData.unionInfo.find(function (ele) {
                return ele.unionID === msg.unionID;
            });
            if (unionInfoItem) {
                totalScore += parseFloat((unionInfoItem.score + (unionInfoItem.saveScore || 0) + unionInfoItem.safeScore).toFixed(2));
            }
        }
        next(null, {
            code: code.OK,
            msg: {
                recordArr,
                recordCount,
                totalCount,
                totalScore
            }
        });
    } catch (e) {
        logger.error(`[getMemberScoreList]` + e.stack);
        next(null, {
            code: 500
        });
    }





};

// 返利操作
Handler.prototype.safeBoxOperation = async function (msg, session, next) {

    logger.info(`[safeBoxOperation] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断玩家数据是否被锁定
        let userData = await userDao.getUnlockUserDataAndLock(session.uid);
        if (!userData) {
            next(null, {
                code: code.USER_DATA_LOCKED
            });
            return;
        }
        // 判断玩家是否正在游戏中
        if (!!userData.roomID) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let unionInfo = null;
        for (let i = 0; i < userData.unionInfo.length; ++i) {
            if (userData.unionInfo[i].unionID === msg.unionID) {
                unionInfo = userData.unionInfo[i];
                break;
            }
        }
        if (!unionInfo) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        let curCount = unionInfo.safeScore;
        if (msg.count) {
            curCount = parseFloat(msg.count);
        }
        // 校验数据是否可以领取
        if (unionInfo.safeScore <= 0 || curCount > unionInfo.safeScore) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        // 更新数据
        let saveData = {
            $inc: {
                "unionInfo.$.score": curCount,
                "unionInfo.$.safeScore": -curCount
            }
        };
        let newUserData = await userDao.updateUserDataAndUnlock({
            uid: session.uid,
            "unionInfo.unionID": unionInfo.unionID
        }, saveData);

        // 存储数据
        let saveRecord = {
            uid: session.uid,
            unionID: msg.unionID,
            count: curCount,
            type: 0,
            createTime: Date.now()
        };
        await commonDao.createData("safeBoxRecordModel", saveRecord);

        // 存储分数变化记录
        let newUnionInfo = newUserData.unionInfo.find(function (e) {
            return e.unionID === msg.unionID;
        });
        curCount = curCount.toFixed(2);
        let scoreChangeRecord = {
            uid: session.uid,
            nickname: newUserData.nickname,
            unionID: msg.unionID,
            changeCount: curCount,
            leftCount: newUnionInfo.score,
            leftSafeBoxCount: newUnionInfo.safeScore,
            leftSaveBoxCount: newUnionInfo.saveScore,
            changeType: enumeration.scoreChangeType.SAFE_BOX,
            describe: ("提取返利" + curCount),
            createTime: Date.now()
        };
        //0721新的变化记录
        await commonDao.createData("userScoreDetailModel", scoreChangeRecord).catch(e => {
            logger.error(e.stack)
        });

        next(null, {
            code: code.OK,
            updateUserData: {
                unionInfo: newUserData.unionInfo
            }
        });
        logger.info(`[safeBoxOperation] operate success`);

    } catch (e) {
        logger.error(`[safeBoxOperation]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

//保险柜存取分数
Handler.prototype.saveBoxOperation = async function (msg, session, next) {

    logger.info(`[saveBoxOperation] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.count || typeof msg.count !== 'number') {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断玩家数据是否被锁定
        let userData = await userDao.getUnlockUserDataAndLock(session.uid);
        if (!userData) {
            next(null, {
                code: code.USER_DATA_LOCKED
            });
            return;
        }
        // 判断玩家是否正在游戏中
        if (!!userData.roomID) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        let unionInfo = null;
        for (let i = 0; i < userData.unionInfo.length; ++i) {
            if (userData.unionInfo[i].unionID === msg.unionID) {
                unionInfo = userData.unionInfo[i];
                break;
            }
        }
        if (!unionInfo) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        // 校验数据,大于0,则是存，小于0则是取
        if ((msg.count > 0 && unionInfo.score < msg.count) || (msg.count < 0 && unionInfo.saveScore + msg.count < 0)) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        // 更新数据
        let saveData = {
            $inc: {
                "unionInfo.$.score": -msg.count,
                "unionInfo.$.saveScore": msg.count
            }
        };
        let newUserData = await userDao.updateUserDataAndUnlock({
            uid: session.uid,
            "unionInfo.unionID": unionInfo.unionID
        }, saveData);
        // 存储数据
        let saveRecord = {
            uid: session.uid,
            unionID: msg.unionID,
            count: msg.count,
            type: 1, //保险柜分数
            createTime: Date.now()
        };
        await commonDao.createData("safeBoxRecordModel", saveRecord);

        // 存储分数变化记录
        let newUnionInfo = newUserData.unionInfo.find(function (e) {
            return e.unionID === msg.unionID;
        });
        let scoreChangeRecord = {
            uid: session.uid,
            nickname: newUserData.nickname,
            unionID: msg.unionID,
            changeCount: -msg.count,
            leftCount: newUnionInfo.score,
            leftSafeBoxCount: (newUnionInfo.safeScore || 0),
            leftSaveBoxCount: (newUnionInfo.saveScore || 0),
            changeType: enumeration.scoreChangeType.SAVE_SCORE,
            describe: msg.count > 0 ? ("保险柜存入" + msg.count) : ("保险柜取出" + msg.count * -1),
            createTime: Date.now()
        };
        //0721新的变化记录
        await commonDao.createData("userScoreDetailModel", scoreChangeRecord).catch(e => {
            logger.error(e.stack)
        });

        next(null, {
            code: code.OK,
            updateUserData: {
                unionInfo: newUserData.unionInfo
            }
        });
        logger.info(`[saveBoxOperation] operate success`);
    } catch (e) {
        logger.error(`[saveBoxOperation]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

// 保险箱操作记录 0:返利 1：存储分数
Handler.prototype.safeBoxOperationRecord = async function (msg, session, next) {

    logger.info(`[safeBoxOperationRecord] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // logger.error(`safeBoxOperationRecord msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let matchData = {
            uid: session.uid,
            unionID: msg.unionID,
            type: msg.type,
            createTime: {
                $gte: Date.now() - WEEK_MS
            }
        };
        let result = await commonDao.findDataAndCount("safeBoxRecordModel", msg.startIndex || 0, msg.count || 20, {
            createTime: -1
        }, matchData);
        next(null, {
            code: code.OK,
            msg: result
        });
    } catch (e) {
        logger.error(`[safeBoxOperationRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

// 修改积分 count > 0 加分 count < 0 减分
Handler.prototype.modifyScore = async function (msg, session, next) {

    logger.info(`[modifyScore] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    if (!userList[session.uid]) {
        userList[session.uid] = moment();
    } else {
        if (moment().diff(userList[session.uid], 's') < 3) {
            next(null, {
                code: code.USER_DATA_LOCKED
            });
            return;
        }
    }
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (unionData && session.uid == msg.memberUid && msg.memberUid == unionData.ownerUid) {

            let userData = await userDao.getUnlockUserDataAndLock(session.uid);
            let newMemberData = await userDao.updateUserDataAndUnlock({
                uid: msg.memberUid,
                "unionInfo.unionID": msg.unionID
            }, {
                $inc: {
                    "unionInfo.$.score": msg.count
                }
            });
            let unionInfoItem = newMemberData.unionInfo.find(item => item.unionID == msg.unionID);
            // 添加修改记录
            let createData = {
                uid: session.uid,
                nickname: userData.nickname,
                avatar: userData.avatar,
                gainUid: msg.memberUid,
                gainNickname: userData.nickname,
                gainAvatar: userData.avatar,
                unionID: msg.unionID,
                gainScore: unionInfoItem.score,
                count: msg.count,
                createTime: Date.now()
            };
            commonDao.createData('scoreModifyRecordModel', createData).catch(e => {
                logger.error(e.stack)
            });
            if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                unionInfo: newMemberData.unionInfo
            }).catch(e => {
                logger.error(e.stack)
            });

            // 存储分数变化记录
            let scoreChangeRecordArr = [];
            let newMemberUnionInfo = newMemberData.unionInfo.find(function (e) {
                return e.unionID === msg.unionID;
            });
            scoreChangeRecordArr.push({
                uid: newMemberData.uid,
                nickname: newMemberData.nickname,
                unionID: msg.unionID,
                changeCount: msg.count,
                leftCount: newMemberUnionInfo.score,
                leftSafeBoxCount: newMemberUnionInfo.safeScore,
                changeType: enumeration.scoreChangeType.MODIFY_UP,
                describe: msg.count > 0 ? ("我给自己[" + userData.uid + "]加积分") : ("我给自己[" + userData.uid + "]减积分"),
                createTime: Date.now()
            });

            //0721新的变化记录
            await commonDao.createDataArr("userScoreDetailModel", scoreChangeRecordArr).catch(e => {
                logger.error(e.stack)
            });
            next(null, {
                code: code.OK,
                updateUserData: {
                    unionInfo: newMemberData.unionInfo
                }
            });
            logger.info(`[modifyScore] operate success owner`);

        } else {

            //普通用户上下分
            if (!msg.unionID || !msg.count || typeof msg.count !== 'number' || !msg.memberUid || session.uid === msg.memberUid) {
                next(null, {
                    code: code.REQUEST_DATA_ERROR
                });
                return;
            }
            if (!unionData) {
                next(null, {
                    code: code.REQUEST_DATA_ERROR
                });
                return;
            }
            if (!!unionData.forbidGive && session.uid !== unionData.ownerUid) {
                next(null, {
                    code: code.FORBID_GIVE_SCORE
                });
                return;
            }
            // 查询用户数据
            let userData = await userDao.getUnlockUserDataAndLock(session.uid);
            if (!userData) {
                next(null, {
                    code: code.REQUEST_DATA_ERROR
                });
                return;
            }
            if (!!userData.roomID) {
                await userDao.unlockUserData(session.uid);
                next(null, {
                    code: code.USER_IN_ROOM_DATA_LOCKED
                });
                return;
            }
            // 判断是否在联盟中
            let userUnionInfoItem = null;
            for (let i = 0; i < userData.unionInfo.length; ++i) {
                if (userData.unionInfo[i].unionID === msg.unionID) {
                    userUnionInfoItem = userData.unionInfo[i];
                    break;
                }
            }
            // 判断积分是否足够
            if (!userUnionInfoItem || (userUnionInfoItem.score < msg.count)) {
                await userDao.unlockUserData(session.uid);
                next(null, {
                    code: code.NOT_ENOUGH_SCORE
                });
                return;
            }

            //新增管理员不能给盟主减分
            if (userUnionInfoItem.manager && msg.count < 0 && msg.memberUid == unionData.ownerUid) {
                await userDao.unlockUserData(session.uid);
                next(null, {
                    code: code.PERMISSION_NOT_ENOUGH
                });
                return;
            }

            // 查询会员数据
            let memberUserData = await userDao.getUnlockUserDataAndLock(msg.memberUid);
            if (!memberUserData) {
                await userDao.unlockUserData(session.uid);
                await userDao.unlockUserData(msg.memberUid);
                next(null, {
                    code: code.USER_IN_ROOM_DATA_LOCKED
                });
                return;
            }
            if (!!memberUserData.roomID && msg.count < 0) {
                await userDao.unlockUserData(msg.memberUid);
                await userDao.unlockUserData(session.uid);
                next(null, {
                    code: code.USER_IN_ROOM_DATA_LOCKED
                });
                return;
            }

            // 判断是否在联盟中
            let memberUnionInfoItem = null;
            for (let i = 0; i < memberUserData.unionInfo.length; ++i) {
                if (memberUserData.unionInfo[i].unionID === msg.unionID) {
                    memberUnionInfoItem = memberUserData.unionInfo[i];
                    break;
                }
            }
            //判断用户分数是否足够
            if (!memberUnionInfoItem || (msg.count < 0 && (memberUnionInfoItem.score + msg.count) < 0)) {
                await userDao.unlockUserData(session.uid);
                await userDao.unlockUserData(msg.memberUid);
                next(null, {
                    code: code.NOT_ENOUGH_SCORE
                });
                return;
            }
            // session.uid == msg.memberUid && msg.memberUid == unionData.ownerUid
            //当前上级 盟主 或者管理员才有权限
            logger.info(`[modifyScore] sessionUid = ${session.uid} ownerUid = ${unionData.ownerUid} isPartner = ${userUnionInfoItem.partner} isManager = ${userUnionInfoItem.manager} spreaderID = ${memberUnionInfoItem.spreaderID}`);
            //不是队长 不是管理员
            if (!userUnionInfoItem.manager && !userUnionInfoItem.partner) {
                await userDao.unlockUserData(session.uid);
                await userDao.unlockUserData(msg.memberUid);
                next(null, {
                    code: code.PERMISSION_NOT_ENOUGH
                });
                return;
            }
            if (memberUnionInfoItem.spreaderID == session.uid || session.uid == unionData.ownerUid || userUnionInfoItem.manager) {
                // 修改分数
                let newUserData = await userDao.updateUserDataAndUnlock({
                    uid: session.uid,
                    "unionInfo.unionID": msg.unionID
                }, {
                    $inc: {
                        "unionInfo.$.score": -msg.count
                    }
                });
                let newMemberData = await userDao.updateUserDataAndUnlock({
                    uid: msg.memberUid,
                    "unionInfo.unionID": msg.unionID
                }, {
                    $inc: {
                        "unionInfo.$.score": msg.count
                    }
                });
                let unionInfoItem = newMemberData.unionInfo.find(item => item.unionID == msg.unionID);
                // 添加修改记录
                let createData = {
                    uid: session.uid,
                    nickname: userData.nickname,
                    avatar: userData.avatar,
                    gainUid: msg.memberUid,
                    gainNickname: memberUserData.nickname,
                    gainAvatar: memberUserData.avatar,
                    unionID: msg.unionID,
                    gainScore: unionInfoItem.score,
                    count: msg.count,
                    createTime: Date.now()
                };
                commonDao.createData('scoreModifyRecordModel', createData).catch(e => {
                    logger.error(e.stack)
                });
                if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                    unionInfo: newMemberData.unionInfo
                }).catch(e => {
                    logger.error(e.stack)
                });

                // 存储分数变化记录
                let newUnionInfo = newUserData.unionInfo.find(function (e) {
                    return e.unionID === msg.unionID;
                });
                let scoreChangeRecordArr = [];
                scoreChangeRecordArr.push({
                    uid: newUserData.uid,
                    nickname: newUserData.nickname,
                    unionID: msg.unionID,
                    changeCount: -msg.count,
                    leftCount: newUnionInfo.score,
                    leftSafeBoxCount: newUnionInfo.safeScore,
                    leftSaveBoxCount: newUnionInfo.saveScore,
                    changeType: enumeration.scoreChangeType.MODIFY_LOW,
                    describe: msg.count > 0 ? "我增加[" + newMemberData.uid + "]积分" : "我减少[" + newMemberData.uid + "]积分",
                    createTime: Date.now()
                });
                let newMemberUnionInfo = newMemberData.unionInfo.find(function (e) {
                    return e.unionID === msg.unionID;
                });
                scoreChangeRecordArr.push({
                    uid: newMemberData.uid,
                    nickname: newMemberData.nickname,
                    unionID: msg.unionID,
                    changeCount: msg.count,
                    leftCount: newMemberUnionInfo.score,
                    leftSafeBoxCount: newMemberUnionInfo.safeScore,
                    leftSaveBoxCount: newMemberUnionInfo.saveScore,
                    changeType: enumeration.scoreChangeType.MODIFY_UP,
                    describe: msg.count > 0 ? "[" + newUserData.uid + "]增加我的积分" : "[" + newUserData.uid + "]减少我的积分",
                    createTime: Date.now()
                });
                //0721新的变化记录
                await commonDao.createDataArr("userScoreDetailModel", scoreChangeRecordArr).catch(e => {
                    logger.error(e.stack)
                });
                next(null, {
                    code: code.OK,
                    updateUserData: {
                        unionInfo: newUserData.unionInfo
                    }
                });
                logger.info(`[modifyScore] operate success`);
            } else {
                //没有权限
                await userDao.unlockUserData(msg.memberUid);
                await userDao.unlockUserData(session.uid);
                next(null, {
                    code: code.UNION_ADD_SCORE_LIMIT
                });
                return;
            }
        }

    } catch (e) {
        logger.error(`[modifyScore]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

// 添加合伙人
Handler.prototype.addPartner = async function (msg, session, next) {

    logger.info(`[addPartner] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 检查邀请权限
        if (!!unionData.forbidInvite) {
            next(null, {
                code: code.FORBID_INVITE_SCORE
            });
            return;
        }

        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[addPartner] ownerUid = ${unionData.ownerUid} isManager = ${userUnionInfoItem.manager} sessionUid = ${session.uid}`);
        // if (unionData.ownerUid != session.uid) {
        //     next(null, {
        //         code: code.PERMISSION_NOT_ENOUGH
        //     });
        //     return;
        // }

        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        //在联盟中
        if (!!memberUnionInfoItem) {

            //如果已经是合伙人
            if (memberUnionInfoItem.partner) {
                next(null, {
                    code: code.OK
                });
                return;
            }
            // 更新用户数据
            let newMemberData = await userDao.updateUserData({
                uid: msg.memberUid,
                "unionInfo.unionID": msg.unionID
            }, {
                "unionInfo.$.partner": true, "unionInfo.$.sortType": 3
            });
            if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                unionInfo: newMemberData.unionInfo
            }).catch(e => {
                logger.error(e.stack)
            });

            let doneUid = newMemberData.uid;
            let doneAvatar = newMemberData.avatar;
            let doneNickname = newMemberData.nickname;
            let uid = userData.uid;
            let avatar = userData.avatar;
            let nickname = userData.nickname;

            await commonDao.createData('userDelModel', {
                type: 2,
                doneUid,
                doneAvatar,
                doneNickname,
                uid,
                avatar,
                nickname,
                score: 0,
                unionID: msg.unionID,
                createTime: Date.now()
            });

            next(null, {
                code: code.OK
            });
            logger.info(`[addPartner] operate success update`);
            return;
        } else {
            // 更新联盟数据
            await commonDao.updateData('unionModel', {
                unionID: msg.unionID
            }, {
                $inc: {
                    curMember: 1
                }
            });
            let doneUid = memberUserData.uid;
            let doneAvatar = memberUserData.avatar;
            let doneNickname = memberUserData.nickname;
            let uid = userData.uid;
            let avatar = userData.avatar;
            let nickname = userData.nickname;

            await commonDao.createData('userDelModel', {
                type: 0,
                doneUid,
                doneAvatar,
                doneNickname,
                uid,
                avatar,
                nickname,
                score: 0,
                unionID: msg.unionID,
                createTime: Date.now()
            });


            await commonDao.createData('userDelModel', {
                type: 2,
                doneUid,
                doneAvatar,
                doneNickname,
                uid,
                avatar,
                nickname,
                score: 0,
                unionID: msg.unionID,
                createTime: Date.now()
            });

            // 加入到联盟中
            let pushData = {
                unionID: msg.unionID,
                spreaderID: session.uid,
                partner: true,
                sortType: 3,
                joinTime: Date.now()
            };
            let uniqueIDData = await commonDao.findOneAndUpdateEx("uniqueIDModel", {
                key: 1
            }, {
                $inc: {
                    unionInviteID: 7
                }
            }, {
                new: true,
                upsert: true
            });
            pushData.inviteID = uniqueIDData.unionInviteID;
            let newMemberData = await userDao.updateUserDataByUid(msg.memberUid, {
                $push: {
                    unionInfo: pushData
                }
            });
            if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
                unionInfo: newMemberData.unionInfo
            }).catch(e => {
                logger.error(e.stack)
            });
            next(null, {
                code: code.OK
            });
            logger.info(`[addPartner] operate success join`);
        }
    } catch (e) {
        logger.error(`[addPartner]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

// 设置联盟管理权限
Handler.prototype.addManager = async function (msg, session, next) {

    logger.info(`[addManager] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        if (session.uid == msg.memberUid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.NOT_IN_UNION
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        // 只有盟主才可以新增管理人员
        if (unionData.ownerUid !== session.uid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        logger.info(`[addManager] ownerUid = ${unionData.ownerUid} sessionUid = ${session.uid}`);
        let isDel = msg.isDel || false;

        // 已经添加过则直接返回
        if (!isDel && memberUnionInfoItem.manager) {
            next(null, {
                code: code.OK
            });
            return;
        }
        //已经不是管理
        if (isDel && !memberUnionInfoItem.manager) {
            next(null, {
                code: code.OK
            });
            return;
        }
        let isManager = isDel ? false : true;
        let sortType = isDel ? 0 : 4;
        let logType = isDel ? 5 : 4;
        // 更新用户数据
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.manager": isManager,
            "unionInfo.$.sortType": sortType
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e.stack)
        });

        //保存记录-设为管理
        let doneUid = newMemberData.uid;
        let doneAvatar = newMemberData.avatar;
        let doneNickname = newMemberData.nickname;
        let uid = userData.uid;
        let avatar = userData.avatar;
        let nickname = userData.nickname;

        await commonDao.createData('userDelModel', {
            type: logType,
            doneUid,
            doneAvatar,
            doneNickname,
            uid,
            avatar,
            nickname,
            score: 0,
            unionID: unionData.unionID,
            createTime: Date.now()
        });


        next(null, {
            code: code.OK
        });
        logger.info(`[addManager] operate success`);

    } catch (e) {
        logger.error(`[addManager]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

// 查看修改积分日志
Handler.prototype.getScoreModifyRecord = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.matchData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let list = await commonDao.findDataAndCount("scoreModifyRecordModel", msg.startIndex, msg.count, {
            createTime: -1
        }, msg.matchData);

        let totalScoreCount = 0; {
            let groupData = {
                _id: null,
                totalCount: {
                    $sum: "$count"
                }
            };
            let execData = [{
                $match: msg.matchData
            }, {
                $group: groupData
            }];
            let result = await commonDao.getStatisticsInfo('scoreModifyRecordModel', execData);

            if (result.length > 0) {
                totalScoreCount = result[0].totalCount;
            }
        }
        next(null, {
            code: code.OK,
            msg: {
                recordArr: list.recordArr,
                totalCount: list.totalCount,
                totalScoreCount: totalScoreCount
            }
        });
    } catch (e) {
        logger.error(`[getScoreModifyRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }



};

// 邀请玩家
Handler.prototype.inviteJoinUnion = async function (msg, session, next) {

    logger.info(`[inviteJoinUnion] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 检查邀请权限
        if (!!unionData.forbidInvite) {
            next(null, {
                code: code.FORBID_INVITE_SCORE
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.uid);
        if (!memberUserData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!!memberUnionInfoItem) {
            next(null, {
                code: code.ALREADY_IN_UNION
            });
            return;
        }
        logger.info(`[inviteJoinUnion] ownerUid = ${unionData.ownerUid} isPartner = ${userUnionInfoItem.partner} isManager = ${userUnionInfoItem.manager}  sessionUid = ${session.uid}`);
        // 检查邀请权限
        if (session.uid !== unionData.ownerUid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        // 更新联盟数据
        await commonDao.updateData('unionModel', {
            unionID: msg.unionID
        }, {
            $inc: {
                curMember: 1
            }
        });

        //保存用户邀请记录
        let doneUid = memberUserData.uid;
        let doneAvatar = memberUserData.avatar;
        let doneNickname = memberUserData.nickname;
        let uid = userData.uid;
        let avatar = userData.avatar;
        let nickname = userData.nickname;

        await commonDao.createData('userDelModel', {
            type: 0,
            doneUid,
            doneAvatar,
            doneNickname,
            uid,
            avatar,
            nickname,
            score: 0,
            unionID: msg.unionID,
            createTime: Date.now()
        });


        // 加入到联盟中
        let pushData = {
            unionID: msg.unionID,
            spreaderID: session.uid,
            partner: msg.partner,
            sortType: msg.partner ? 3 : 0,
            joinTime: Date.now()
        };
        let uniqueIDData = await commonDao.findOneAndUpdateEx("uniqueIDModel", { key: 1 }, { $inc: { unionInviteID: 7 } }, { new: true, upsert: true });
        pushData.inviteID = uniqueIDData.unionInviteID;
        let newMemberData = await userDao.updateUserDataByUid(msg.uid, {
            $push: {
                unionInfo: pushData
            }
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e.stack)
        });
        next(null, {
            code: code.OK
        });
        logger.info(`[inviteJoinUnion] operate success`);
    } catch (e) {
        logger.error(`[inviteJoinUnion]` + e.stack);
        next(null, {
            code: 500
        });
    }



};

// 操作俱乐部邀请
Handler.prototype.operationInviteJoinUnion = async function (msg, session, next) {

    logger.info(`[operationInviteJoinUnion] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.uid || !msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let userData = await userDao.getUserDataByUid(session.uid);
        let inviteMsgItem = userData.inviteMsg.find(function (element) {
            return element.unionID === msg.unionID && element.uid === msg.uid;
        });
        if (!inviteMsgItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        async function clearInviteMsg(updateData) {
            return await userDao.updateUserDataByUid(session.uid, updateData);
        }
        // 拒绝则直接删除邀请信息
        if (!msg.agree) {
            let newUserData = await clearInviteMsg({
                $pull: {
                    inviteMsg: {
                        unionID: msg.unionID,
                        uid: msg.uid
                    }
                }
            });
            next(null, {
                code: code.OK,
                updateUserData: {
                    inviteMsg: newUserData.inviteMsg
                }
            });
            return;
        }
        // 判断是否已经达到玩家最大联盟数
        if (userData.unionInfo.length >= 20) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        // 联盟不存在，则删除该联盟的信息
        if (!unionData) {
            let newUserData = await clearInviteMsg({
                $pull: {
                    inviteMsg: {
                        unionID: msg.unionID
                    }
                }
            });
            next(null, {
                code: code.REQUEST_DATA_ERROR,
                updateUserData: {
                    inviteMsg: newUserData.inviteMsg
                }
            });
            return;
        }
        // 如果已经在联盟中，则删除联盟信息
        let unionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!!unionInfoItem) {
            let newUserData = await clearInviteMsg({
                $pull: {
                    inviteMsg: {
                        unionID: msg.unionID
                    }
                }
            });
            next(null, {
                code: code.OK,
                updateUserData: {
                    inviteMsg: newUserData.inviteMsg
                }
            });
            return;
        }
        // logger.error(`operationInviteJoinUnion msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 更新联盟数据
        await commonDao.updateData('unionModel', {
            unionID: msg.unionID
        }, {
            $inc: {
                curMember: 1
            }
        });
        // 加入到联盟中
        let pushData = {
            unionID: msg.unionID,
            spreaderID: msg.uid,
            partner: inviteMsgItem.partner,
            joinTime: Date.now()
        };
        let uniqueIDData = await commonDao.findOneAndUpdateEx("uniqueIDModel", {
            key: 1
        }, {
            $inc: {
                unionInviteID: 7
            }
        }, {
            new: true,
            upsert: true
        });
        pushData.inviteID = uniqueIDData.unionInviteID;
        let newUserData = await userDao.updateUserDataByUid(session.uid, {
            $push: {
                unionInfo: pushData
            },
            $pull: {
                inviteMsg: {
                    unionID: msg.unionID
                }
            }
        });
        next(null, {
            code: code.OK,
            updateUserData: {
                inviteMsg: newUserData.inviteMsg,
                unionInfo: newUserData.unionInfo
            }
        });
    } catch (e) {
        logger.error(`[operationInviteJoinUnion]` + e.stack);
        next(null, {
            code: 500
        });
    }



};


// 更新返利比例
Handler.prototype.updateUnionTicketRebate = async function (msg, session, next) {
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }

        msg.rebateRate = msg.ticketRate;

        if (!msg.unionID || !msg.memberUid || typeof msg.rebateRate !== 'number' || msg.rebateRate > 1 || msg.rebateRate < 0) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        // 判断是否在联盟中，并且是否是该会员的上级用户
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!memberUnionInfoItem || memberUnionInfoItem.spreaderID !== session.uid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 更新比例
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.ticketRate": msg.rebateRate,
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e)
        });

        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[updateUnionTicketRebate]` + e.stack);
        next(null, {
            code: 500
        });
    }
};


// 更新返利比例
Handler.prototype.updateUnionRebate = async function (msg, session, next) {
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid || typeof msg.rebateRate !== 'number' || msg.rebateRate > 1 || msg.rebateRate < 0) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem || userUnionInfoItem.rebateRate < msg.rebateRate) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        // 判断是否在联盟中，并且是否是该会员的上级用户
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!memberUnionInfoItem || memberUnionInfoItem.spreaderID !== session.uid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // logger.error(`updateUnionRebate msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 更新比例
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.rebateRate": msg.rebateRate
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e)
        });

        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[updateUnionRebate]` + e.stack);
        next(null, {
            code: 500
        });
    }
};


// 修改合伙人警戒线
Handler.prototype.updateLimitScore = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid || typeof msg.limitScore !== 'number') {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        // 判断是否在联盟中，并且是否是该会员的上级用户
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!memberUnionInfoItem || memberUnionInfoItem.spreaderID !== session.uid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // logger.error(`updateLimitScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 更新分数限制
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.limitScore": msg.limitScore
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e)
        });

        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[updateLimitScore]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

// 修改合伙人显示保底流水
Handler.prototype.updateShowFixScore = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        //只能盟主操作
        // if (!unionData || (unionData.ownerUid !== session.uid)) {
        //     next(null, { code: code.PERMISSION_NOT_ENOUGH });
        //     return;
        // }

        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        // 判断是否在联盟中
        let userUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        if (unionData.ownerUid !== session.uid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        //logger.error(`updateShowFixScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let isShow = msg.isShow == 1 ? true : false;
        // 更新分数限制
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.showFixScore": isShow
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e)
        });

        let result = {
            code: code.OK,
            'isShow': msg.isShow
        };
        next(null, result);
    } catch (e) {
        logger.error(`[updateShowFixScore]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

//修改合伙人的保底返利
Handler.prototype.updateUserFixScore = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        //只能盟主操作
        // if (!unionData || (unionData.ownerUid !== session.uid)) {
        //     next(null, { code: code.PERMISSION_NOT_ENOUGH });
        //     return;
        // }

        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }

        // 判断是否在联盟中
        let userUnionInfoItem = memberUserData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        if (unionData.ownerUid !== session.uid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        // logger.error(`updateUserFixScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let fixScoreRate = msg.fixScoreRate || 0;
        // 更新分数限制
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.fixScoreRate": fixScoreRate
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e)
        });

        let result = {
            code: code.OK,
            'fixScoreRate': msg.fixScoreRate
        };
        next(null, result);
    } catch (e) {
        logger.error(`[updateUserFixScore]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

//更新联盟公告
Handler.prototype.updateUnionNotice = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.notice || msg.notice.length > 40) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        //logger.error(`updateUnionNotice msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let newUserData = await userDao.updateUserData({
            uid: session.uid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.notice": msg.notice
        });
        next(null, {
            code: code.OK,
            updateUserData: {
                unionInfo: newUserData.unionInfo
            }
        });
    } catch (e) {
        logger.error(`[updateUnionNotice]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

// 赠送积分
Handler.prototype.giveScore = async function (msg, session, next) {
    logger.info(`[giveScore] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        msg.count = parseInt(msg.count);
        if (!msg.unionID || typeof msg.count !== 'number' || msg.count <= 0 || !msg.giveUid || session.uid === msg.giveUid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查看赠送权限
        if (!!unionData.forbidGive && session.uid !== unionData.ownerUid) {
            next(null, {
                code: code.FORBID_GIVE_SCORE
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUnlockUserDataAndLock(session.uid);
        if (!userData || !!userData.roomID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        // 非盟主时需要判断积分是否足够,盟主时不需要判断分数
        if (!userUnionInfoItem || (userUnionInfoItem.score < msg.count && session.uid !== unionData.ownerUid)) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.giveUid);
        if (!memberUserData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        if (!memberUnionInfoItem) {
            await userDao.unlockUserData(session.uid);
            next(null, {
                code: code.NOT_IN_UNION
            });
            return;
        }
        //logger.error(`giveScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 修改分数
        let newUserData = null;
        // 非盟主时，需改对应修改分数数量
        //if (session.uid !== unionData.ownerUid) {
        newUserData = await userDao.updateUserDataAndUnlock({
            uid: session.uid,
            "unionInfo.unionID": msg.unionID
        }, {
            $inc: {
                "unionInfo.$.score": -msg.count
            }
        });
        // }
        // 盟主时，不需要修改
        //else {
        //    await userDao.unlockUserData(session.uid);
        //    newUserData = userData;
        //}
        let newMemberData = await userDao.updateUserData({
            uid: msg.giveUid,
            "unionInfo.unionID": msg.unionID
        }, {
            $inc: {
                "unionInfo.$.score": msg.count
            }
        });
        // 添加修改记录
        let createData = {
            uid: session.uid,
            nickname: newUserData.nickname,
            gainUid: msg.giveUid,
            gainNickname: memberUserData.nickname,
            gainAvatar: memberUserData.avatar,
            unionID: msg.unionID,
            count: msg.count,
            createTime: Date.now()
        };
        commonDao.createData('scoreGiveRecordModel', createData).catch(e => {
            logger.error(e.stack)
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e.stack)
        });

        // 存储分数变化记录
        let newUnionInfo = newUserData.unionInfo.find(function (e) {
            return e.unionID === msg.unionID;
        });
        let scoreChangeRecordArr = [];
        scoreChangeRecordArr.push({
            uid: newUserData.uid,
            nickname: newUserData.nickname,
            unionID: msg.unionID,
            changeCount: -msg.count,
            leftCount: newUnionInfo.score,
            leftSafeBoxCount: newUnionInfo.safeScore,
            leftSaveBoxCount: newUnionInfo.saveScore,
            changeType: enumeration.scoreChangeType.GIVE,
            describe: "赠送积分给玩家[" + newMemberData.uid + "]",
            createTime: Date.now()
        });
        let newMemberUnionInfo = newMemberData.unionInfo.find(function (e) {
            return e.unionID === msg.unionID;
        });
        scoreChangeRecordArr.push({
            uid: newMemberData.uid,
            nickname: newMemberData.nickname,
            unionID: msg.unionID,
            changeCount: msg.count,
            leftCount: newMemberUnionInfo.score,
            leftSafeBoxCount: newMemberUnionInfo.safeScore,
            leftSaveBoxCount: newMemberUnionInfo.saveScore,
            changeType: enumeration.scoreChangeType.GIVE,
            describe: '玩家[' + newUserData.uid + "]赠送给我积分",
            createTime: Date.now()
        });
        //0721新的变化记录
        await commonDao.createDataArr("userScoreDetailModel", scoreChangeRecordArr).catch(e => {
            logger.error(e.stack)
        });
        next(null, {
            code: code.OK,
            updateUserData: {
                unionInfo: newUserData.unionInfo
            }
        });
    } catch (e) {
        logger.error(`[giveScore]` + e.stack);
        next(null, {
            code: code.OK
        });
    }
};

// 获取成员列表
Handler.prototype.getGiveScoreRecord = async function (msg, session, next) {
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.matchData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        //logger.error(`getGiveScoreRecord msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let res = await commonDao.findDataAndCount('scoreGiveRecordModel', msg.startIndex || 0, msg.count || 20, {
            createTime: -1
        }, msg.matchData);
        let totalGiveCount = 0;
        // 获取赠送总额
        if (!!msg.total) {
            let groupData = {
                _id: null,
                totalGiveCount: {
                    $sum: "$count"
                }
            };
            let execData = [{
                $match: {
                    uid: session.uid,
                    unionID: msg.unionID
                }
            },
            {
                $group: groupData
            }
            ];
            let result = await commonDao.getStatisticsInfo('scoreGiveRecordModel', execData);

            if (result.length > 0) {
                totalGiveCount = result[0].totalGiveCount;
            }
        }
        let totalGainCount = 0;
        // 获取受赠总额
        if (!!msg.total) {
            let groupData = {
                _id: null,
                totalGiveCount: {
                    $sum: "$count"
                }
            };
            let execData = [{
                $match: {
                    gainUid: session.uid,
                    unionID: msg.unionID
                }
            },
            {
                $group: groupData
            }
            ];
            let result = await commonDao.getStatisticsInfo('scoreGiveRecordModel', execData);

            if (result.length > 0) {
                totalGainCount = result[0].totalGiveCount;
            }
        }

        let data = {
            recordArr: res.recordArr,
            totalCount: res.totalCount,
        };
        if (msg.total) {
            data.totalGiveCount = totalGiveCount;
            data.totalGainCount = totalGainCount
        }
        next(null, {
            code: code.OK,
            msg: data
        });
    } catch (e) {
        logger.error(`[getGiveScoreRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

// 获取成员列表
Handler.prototype.getUnionRebateRecord = async function (msg, session, next) {

    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.matchData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let res = await commonDao.findDataAndCount('userRebateRecordModel', msg.startIndex || 0, msg.count || 20, {
            createTime: -1
        }, msg.matchData);
        next(null, {
            code: code.OK,
            msg: {
                recordArr: res.recordArr,
                totalCount: res.totalCount
            }
        });
    } catch (e) {
        logger.error(`[getUnionRebateRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }

};


// 获取回放数据
Handler.prototype.getGameReplay = async function (msg, session, next) {

    try {

        if (!session.uid) {
            next(null, { code: code.INVALID_UERS });
            return;
        }
        //回放码
        if (!msg.replayCode) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        let res = await commonDao.findOneData('userGameRecordModel', { 'index': msg.replayCode });
        next(null, {
            code: code.OK,
            msg: res
        });
    } catch (e) {
        logger.error(`[getGameReplay]` + e.stack);
        next(null, {
            code: 500
        });
    }

};


// 获取成员战绩
Handler.prototype.getGameRecord = async function (msg, session, next) {

    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.matchData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let userID = msg.uid;
        let res = await commonDao.findDataAndCountFilter('userGameRecordModel', msg.startIndex || 0, msg.count || 20, { createTime: -1 }, msg.matchData, '-detail');
        //logger.info(`[getGameRecord]` + JSON.stringify(msg.matchData));
        //统计今天的总局数 大赢家数量和所有分数统计
        let allData = await commonDao.findDataAndCountFilter('userGameRecordModel', 0, 0, { createTime: -1 }, msg.matchData, '-detail');

        let totalRate = 0;
        if (msg.isRate == 1) {
            let lowUserList = await userInfoServices.getUserLowAll(userID, msg.unionID);
            totalRate = await userInfoServices.getRebateTotal(lowUserList, msg.dayTime, msg.unionID);
        }

        //let totalDraw = allData.totalCount || 0; //总局数
        let totalDraw = 0; //总局数
        let totalWinDraw = 0; //赢家局数
        let totalbigWinDraw = 0; //大赢家局数
        let totalWin = 0; //总输赢
        let totalRecord = allData.recordArr;
        for (let i = 0; i < totalRecord.length; i++) {

            let curDetail = totalRecord[i];
            let userList = curDetail.userList;
            let bigWinUser = null;
            let maxScore = 0;
            for (let k = 0; k < userList.length; k++) {
                let scoreDetail = userList[k];
                if (scoreDetail.score > maxScore) {
                    maxScore = scoreDetail.score;
                    bigWinUser = scoreDetail.uid;
                }
                if (scoreDetail.uid == userID) {
                    totalDraw += 1;
                    totalWin += scoreDetail.score;
                    if (scoreDetail.score > 0) {
                        totalWinDraw += 1;
                    }
                }
            }
            if (bigWinUser == userID) {
                totalbigWinDraw += 1;
            }
        }
        next(null, {
            code: code.OK,
            msg: {
                totalRate: totalRate,
                recordArr: res.recordArr,
                totalCount: res.totalCount,
                totalDraw,
                totalbigWinDraw,
                totalWinDraw,
                totalWin
            }
        });
    } catch (e) {
        logger.error(`[getGameRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

// 获取游戏录像
Handler.prototype.getVideoRecord = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.videoRecordID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let res = await commonDao.findOneData('gameVideoRecordModel', {
            videoRecordID: msg.videoRecordID
        });
        next(null, {
            code: code.OK,
            msg: {
                gameVideoRecordData: res
            }
        });
    } catch (e) {
        logger.error(`[getVideoRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

// 更新禁止游戏状态
Handler.prototype.updateForbidGameStatus = async function (msg, session, next) {


    try {

        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.uid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }


        let curUserData = await userDao.getUserDataByUid(session.uid);
        let unionInfoItem = curUserData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });

        if (!unionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        let forbid = msg.forbid || false;
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData || (unionData.ownerUid !== session.uid && !unionInfoItem.manager)) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(msg.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        if (userData.prohibitGame === forbid) {
            next(null, {
                code: code.OK
            });
            return;
        }
        // logger.error(`updateForbidGameStatus msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let newUserData = await userDao.updateUserData({
            uid: msg.uid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.prohibitGame": forbid
        });
        if (!!newUserData.frontendId) userInfoServices.updateUserDataNotify(newUserData.uid, newUserData.frontendId, {
            unionInfo: newUserData.unionInfo
        }).catch(e => {
            logger.error(e.stack)
        });

        let type = msg.forbid ? 7 : 8;

        //保存用户删除记录
        let doneUid = newUserData.uid;
        let doneAvatar = newUserData.avatar;
        let doneNickname = newUserData.nickname;
        let uid = curUserData.uid;
        let avatar = curUserData.avatar;
        let nickname = curUserData.nickname;

        await commonDao.createData('userDelModel', {
            type: type,
            doneUid,
            doneAvatar,
            doneNickname,
            uid,
            avatar,
            nickname,
            score: 0,
            unionID: unionData.unionID,
            createTime: Date.now()
        });


        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[updateForbidGameStatus]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

// 更新禁止游戏状态
Handler.prototype.getRank = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.matchData || !msg.sortData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        let userData = await userDao.getUserDataByUid(session.uid);
        let unionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });

        if (!unionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        //logger.error(`getRank msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData || (unionData.ownerUid !== session.uid && !unionInfoItem.manager && !unionData.showRank)) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let aggregateData = [{
            '$unwind': "$unionInfo"
        }, {
            '$match': msg.matchData
        },
        {
            '$sort': msg.sortData
        },
        {
            '$skip': msg.startIndex || 0
        },
        {
            '$limit': msg.count || 10
        }
        ];
        let res = await commonDao.getStatisticsInfo("userModel", aggregateData);
        let recordArr = [];
        for (let i = 0; i < res.length; ++i) {
            let user = res[i];
            let unionInfoItem = user.unionInfo;
            if (!unionInfoItem) continue;
            recordArr.push({
                uid: user.uid,
                nickname: user.nickname,
                avatar: user.avatar,
                todayWin: unionInfoItem.todayWin || 0,
                todayDraw: unionInfoItem.todayDraw,
                weekDraw: unionInfoItem.weekDraw || 0,
                totalDraw: unionInfoItem.totalDraw || 0,
                score: unionInfoItem.score || 0,
                yesterdayWin: unionInfoItem.yesterdayWin || 0
            })
        }
        next(null, {
            code: code.OK,
            msg: {
                recordArr: recordArr
            }
        });
    } catch (e) {
        logger.error(`[getRank]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

// 更新单局游戏状态
Handler.prototype.getRankSingleDraw = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.matchData || !msg.sortData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        let userData = await userDao.getUserDataByUid(session.uid);
        let unionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });

        if (!unionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // logger.error(`getRankSingleDraw msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData || (unionData.ownerUid !== session.uid && !unionInfoItem.manager && !unionData.showSingleRank)) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        msg.matchData.createTime = {
            $gte: utils.getTimeTodayStart()
        };
        let groupData = {
            _id: '$userList.uid',
            nickname: {
                $first: "$userList.nickname"
            },
            avatar: {
                $first: "$userList.avatar"
            },
        };
        if (msg.sortData.score === 1) {
            groupData.score = {
                $min: "$userList.score"
            }
        } else {
            groupData.score = {
                $max: "$userList.score"
            }
        }
        let aggregateData = [{
            '$match': msg.matchData
        },
        {
            $unwind: "$userList"
        },
        {
            '$match': msg.matchData
        },
        {
            $group: groupData
        },
        {
            '$sort': msg.sortData
        },
        {
            '$skip': msg.startIndex || 0
        },
        {
            '$limit': msg.count || 10
        }
        ];
        let res = await commonDao.getStatisticsInfo("userGameRecordModel", aggregateData);
        let recordArr = [];
        for (let i = 0; i < res.length; ++i) {
            let userList = res[i];
            userList.uid = userList._id;
            recordArr.push(userList);
        }
        next(null, {
            code: code.OK,
            msg: {
                recordArr: recordArr
            }
        });
    } catch (e) {
        logger.error(`[getRankSingleDraw]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

//await commonDao.updateDataEx("userScoreModel", { uid, unionID, dayTime }, saveData, { upsert: true }).catch(err => { logger.error(err); });
Handler.prototype.userLimitAdd = async function (msg, session, next) {

    try {
        // logger.info(`[hall-unionHandler] userLimitAdd begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.list || !msg.uid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        //  logger.error(`userLimitAdd msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        commonDao.updateDataEx("gameLimitModel", {
            uid: msg.uid,
            unionID: msg.unionID
        }, {
            uid: msg.uid,
            unionID: msg.unionID,
            list: msg.list
        }, {
            upsert: true
        }).catch(err => {
            logger.error(err);
        });
        // logger.info(`[hall-unionHandler] userLimitAdd end`);
        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[userLimitAdd]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//查询玩家限制记录
Handler.prototype.userLimitRecord = async function (msg, session, next) {

    try {
        // logger.info(`[hall-unionHandler] userLimitRecord begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.uid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let matchData = {
            uid: msg.uid,
            unionID: msg.unionID
        };
        //  logger.error(`userLimitRecord msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let result = await commonDao.findOneData("gameLimitModel", matchData);
        // logger.info(`[hall-unionHandler] userLimitRecord end`);
        next(null, {
            code: code.OK,
            msg: result
        });
    } catch (e) {
        logger.error(`[userLimitRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//查询玩家删除记录
Handler.prototype.userDelRecord = async function (msg, session, next) {

    try {
        // logger.info(`[hall-unionHandler] userDelRecord begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let type = msg.type;
        let matchData = {
            unionID: msg.unionID,
        };
        if (msg.isPartner) {
            matchData.uid = session.uid
        }
        if (type != undefined) {
            matchData.type = type;
        }
        if (msg.doneUid) {
            matchData.doneUid = msg.doneUid;
        }
        // logger.info(`userDelRecord msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let result = await commonDao.findDataAndCount("userDelModel", msg.startIndex || 0, msg.count || 20, {
            createTime: -1
        }, matchData);
        // logger.info(`[hall-unionHandler] userDelRecord end`);
        next(null, {
            code: code.OK,
            msg: result
        });
    } catch (e) {
        logger.error(`[userDelRecord]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//将玩家移除联盟
Handler.prototype.deleteUserForUnion = async function (msg, session, next) {

    logger.info(`[deleteUserForUnion] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData("unionModel", {
            unionID: msg.unionID
        });
        if (!unionData) {
            let newUserData = await userDao.updateUserDataByUid(session.uid, {
                $push: { unionInfo: { unionID: msg.unionID } }
            });
            next(null, {
                code: code.OK,
                updateUserData: { unionInfo: newUserData.unionInfo }
            });
            return;
        }
        // 不能删除盟主
        if (unionData.ownerUid === msg.uid) {
            next(null, { code: code.REQUEST_DATA_ERROR });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserData({
            uid: msg.uid,
            "unionInfo.unionID": msg.unionID
        });
        if (!userData) {
            next(null, {
                code: code.OK
            });
            return;
        }
        // 判断玩家是否正在游戏中
        if (!!userData.roomID) {
            next(null, {
                code: code.USER_IN_ROOM_DATA_LOCKED
            });
            return;
        }
        // 查询俱乐部信息
        let unionInfoItem = null;
        for (let i = 0; i < userData.unionInfo.length; ++i) {
            if (userData.unionInfo[i].unionID === msg.unionID) {
                unionInfoItem = userData.unionInfo[i];
                break;
            }
        }
        if (!unionInfoItem) {
            next(null, {
                code: code.OK
            });
            return;
        }

        // 查询用户数据
        let userPartenerData = await userDao.getUserDataByUid(session.uid);
        if (!userPartenerData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否是盟主
        let userUnionInfoItem = userPartenerData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        logger.info(`[deleteUserForUnion] ownerUid = ${unionData.ownerUid} spreaderID = ${unionInfoItem.spreaderID} isPartner = ${userUnionInfoItem.partner}  isManager = ${unionInfoItem.manager} sessionUid = ${session.uid}`);

        if (!userUnionInfoItem.partner) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        //不是上级不能删除或者不是盟主
        if (session.uid != unionInfoItem.spreaderID && session.uid != unionData.ownerUid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        //玩家的钱给盟主
        let totalCount = parseFloat((unionInfoItem.score + unionInfoItem.safeScore + (unionInfoItem.saveScore || 0)).toFixed(2));
        //大于一块不能删除
        if (totalCount > 1) {
            next(null, {
                code: code.CAN_NOT_DELETE_USER_SCORE
            });
            return;
        }
        let newMemberData = await userDao.updateUserData({
            uid: unionData.ownerUid,
            "unionInfo.unionID": msg.unionID
        }, {
            $inc: {
                "unionInfo.$.score": totalCount
            }
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e.stack);
        });

        //保存用户删除记录
        let doneUid = userData.uid;
        let doneAvatar = userData.avatar;
        let doneNickname = userData.nickname;
        let delUser = await userDao.getUserDataByUid(session.uid);
        let uid = delUser.uid;
        let avatar = delUser.avatar;
        let nickname = delUser.nickname;

        await commonDao.createData('userDelModel', {
            type: 1,
            doneUid,
            doneAvatar,
            doneNickname,
            uid,
            avatar,
            nickname,
            score: totalCount,
            unionID: msg.unionID,
            createTime: Date.now()
        });

        // 删除联盟数据
        let newUserData = await userDao.updateUserDataByUid(msg.uid, {
            $pull: {
                unionInfo: {
                    unionID: msg.unionID
                }
            },
            unionID: 0,
            isBind: false
        });
        if (!!newUserData.frontendId) userInfoServices.updateUserDataNotify(newUserData.uid, newUserData.frontendId, {
            unionInfo: newUserData.unionInfo
        }).catch(e => {
            logger.error(e.stack);
        });
        // 将下级用户转移给上级玩家
        await commonDao.updateAllData("userModel", {
            unionInfo: { $elemMatch: { spreaderID: msg.uid, unionID: msg.unionID } }
        }, {
            "unionInfo.$.spreaderID": unionInfoItem.spreaderID
        });
        // 更新俱乐部人数
        await commonDao.updateData("unionModel", { unionID: msg.unionID }, { $inc: { curMember: -1 } }).catch(e => { logger.error(e.stack) });
        //next(null, { code: code.OK, updateUserData: { unionInfo: newUserData.unionInfo } });
        next(null, { code: code.OK });
        logger.info(`[deleteUserForUnion] operate success`);

    } catch (e) {
        logger.error(`[deleteUserForUnion]` + e.stack);
        next(null, {
            code: 500
        });
    }


};

// 修改队长改为玩家
Handler.prototype.removeCaptainPartner = async function (msg, session, next) {

    logger.info(`[removeCaptainPartner] msg = ${getSimData(msg)} sessionUid = ${session.uid}`);
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid || !msg.operationUid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否是盟主
        let userUnionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        if (!userUnionInfoItem || unionData.ownerUid != session.uid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询用户数据
        let partnerData = await userDao.getUserDataByUid(msg.operationUid);
        if (!partnerData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let parterUnionInfoItem = partnerData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        // 如果不是合伙人
        if (!parterUnionInfoItem || !parterUnionInfoItem.partner) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        // 玩家不在联盟中 
        if (!memberUnionInfoItem) {
            next(null, {
                code: code.NOT_IN_UNION
            });
            return;
        }
        //玩家不是队长
        if (!memberUnionInfoItem.partner) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        //查询玩家的所有下级
        let userList = await userInfoServices.getUserLowAll(memberUserData.uid, msg.unionID);
        userList = userList.filter(item => item != msg.memberUid);
        if (userList.length > 0) {
            next(null, {
                code: code.TANSFER_LEVEL_CAPTAIN
            });
            return;
        }
        // 更新用户数据
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.partner": msg.isPartner,
            "unionInfo.$.ticketRate": 0,
            "unionInfo.$.sortType": msg.partner ? 3 : 0,
            "unionInfo.$.rebateRate": 0
        });
        // 更新用户数据
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e.stack)
        });

        //保存记录-取消组长
        let doneUid = newMemberData.uid;
        let doneAvatar = newMemberData.avatar;
        let doneNickname = newMemberData.nickname;
        let uid = userData.uid;
        let avatar = userData.avatar;
        let nickname = userData.nickname;

        await commonDao.createData('userDelModel', {
            type: 3,
            doneUid,
            doneAvatar,
            doneNickname,
            uid,
            avatar,
            nickname,
            score: 0,
            unionID: unionData.unionID,
            createTime: Date.now()
        });

        next(null, {
            code: code.OK
        });
        logger.info(`[removeCaptainPartner] operate success`);
    } catch (e) {
        logger.error(`[removeCaptainPartner]` + e.stack);
        next(null, {
            code: 500
        });
    }
};

//获取团队保底抽水
Handler.prototype.getTeamFixScore = async function (msg, session, next) {


    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }

        // 联盟信息
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.UNION_NOT_EXIST
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (element) {
            return element.unionID === msg.unionID;
        });

        if (!userUnionInfoItem) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }

        //如果不是管理员或者合伙人或者没有查看权限
        if (unionData.ownerUid != session.uid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // logger.error(`getTeamFixScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        //如果是管理员 则查询盟主的数据
        let curUid = session.uid;
        if (userUnionInfoItem.manager) {
            curUid = unionData.ownerUid;
        }
        parterQuery = {
            unionInfo: {
                $elemMatch: {
                    unionID: msg.unionID,
                    spreaderID: curUid,
                    partner: true
                }
            }
        };

        let userArr = await commonDao.findDataAndCount('userModel', msg.startIndex || 0, msg.count || 20, {
            'unionInfo.fixScoreRate': -1
        }, parterQuery);
        let recordCount = userArr.totalCount;
        let recordArr = [];

        for (let i = 0; i < userArr.recordArr.length; i++) {

            let userData = userArr.recordArr[i];
            // 判断是否在联盟中
            let userUnionInfoItem = userData.unionInfo.find(function (element) {
                return element.unionID === msg.unionID;
            });
            let showFixScore = userUnionInfoItem.showFixScore || false;
            let fixScoreRate = userUnionInfoItem.fixScoreRate || 0;
            //统计需要减去自己的分数
            recordArr.push({

                uid: userData.uid,
                nickname: utils.getNickName(userData.nickname),
                avatar: userData.avatar,
                showFixScore: showFixScore,
                fixScoreRate: fixScoreRate,
            })
        }

        let msgData = {
            recordCount,
            recordArr
        };
        next(null, {
            code: code.OK,
            msg: msgData
        });
    } catch (e) {
        logger.error(`[getTeamFixScore]` + e.stack);
        next(null, {
            code: 500
        });
    }



}

//设置玩家输赢限制（低于目标分增加分到目标后使用 高于目标分减少到目标分使用）
Handler.prototype.setWinningLimitScore = async function (msg, session, next) {
    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        if (session.uid == msg.memberUid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 判断是否在联盟中
        let userUnionInfoItem = userData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        if (!userUnionInfoItem) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询会员数据
        let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
        if (!memberUserData) {
            next(null, {
                code: code.NOT_IN_UNION
            });
            return;
        }
        // 判断是否在联盟中
        let memberUnionInfoItem = memberUserData.unionInfo.find(function (ele) {
            return ele.unionID === msg.unionID;
        });
        // 只有盟主和管理人员 才能操作
        if (unionData.ownerUid !== session.uid && !memberUnionInfoItem.manager) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // logger.error(`setWinningLimitScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);

        // 更新用户数据
        let newMemberData = await userDao.updateUserData({
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }, {
            "unionInfo.$.targetScore": msg.targetScore,
            "unionInfo.$.floatScore": msg.floatScore,
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e.stack)
        });

        next(null, {
            code: code.OK
        });
    } catch (e) {
        logger.error(`[setWinningLimitScore]` + e.stack);
        next(null, {
            code: 500
        });
    }
}

//查询玩家钻石消耗记录
Handler.prototype.userPayDetailModel = async function (msg, session, next) {

    try {
        // logger.info(`[hall-unionHandler] userPayDetailModel begin`);
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let matchData = {
            unionID: msg.unionID
        };
        // logger.error(`teamDataModel msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let result = await commonDao.findDataAndCount("teamDataModel", msg.startIndex || 0, msg.count || 20, {
            createTime: -1
        }, matchData);
        //  logger.info(`[hall-unionHandler] teamDataModel end`);
        next(null, {
            code: code.OK,
            msg: result
        });
    } catch (e) {
        logger.error(`[userPayDetailModel]` + e.stack);
        next(null, {
            code: 500
        });
    }

};

//查询玩家直系所有上级
Handler.prototype.userDirectSeriesSuperior = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || !msg.memberUid) {
            next(null, {
                code: code.PERMISSION_NOT_ENOUGH
            });
            return;
        }
        // logger.error(`userDirectSeriesSuperior msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        let result = [];
        let Subordinate = msg.memberUid; //操作ID
        let memberUserData = await userDao.getUserDataByUid(Subordinate);
        if (!memberUserData) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        let xianzhi = 0;
        do {
            xianzhi++;
            // 联盟信息
            let memberUserData = await userDao.getUserDataByUid(Subordinate);
            if (!memberUserData) {
                break;
            }
            // 判断是否在联盟中
            let userUnionInfoItem = memberUserData.unionInfo.find(function (element) {
                return element.unionID === msg.unionID;
            });
            if (!userUnionInfoItem) {
                next(null, {
                    code: code.PERMISSION_NOT_ENOUGH
                });
                return;
            } else {
                result.push({
                    nickname: memberUserData.nickname,
                    avatar: memberUserData.avatar,
                    score: userUnionInfoItem.score,
                    partner: userUnionInfoItem.partner,
                    manager: userUnionInfoItem.manager,
                    spreaderID: userUnionInfoItem.spreaderID,
                    ownerUid: unionData.ownerUid,
                    uid: memberUserData.uid,
                })
                Subordinate = userUnionInfoItem.spreaderID;
            }
        }
        while (xianzhi < 2)
        let gameUserPourinfo = [];
        while (result.length > 0) {
            gameUserPourinfo.push(result.pop());
        }
        next(null, {
            code: code.OK,
            msg: {
                spreadsList: gameUserPourinfo
            }
        });
    } catch (e) {
        logger.error(`[userDirectSeriesSuperior]` + e.stack);
        next(null, {
            code: 500
        });
    }

};


Handler.prototype.updateUserRate = async function (msg, session, next) {

    try {
        if (!session.uid) {
            next(null, {
                code: code.INVALID_UERS
            });
            return;
        }
        if (!msg.unionID || (!msg.type && !msg.memberUid)) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }
        // 查询联盟数据
        let unionData = await commonDao.findOneData('unionModel', {
            unionID: msg.unionID
        });
        if (!unionData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        //只能盟主操作
        // if (!unionData || (unionData.ownerUid !== session.uid)) {
        //     next(null, { code: code.PERMISSION_NOT_ENOUGH });
        //     return;
        // }

        // 查询用户数据
        let userData = await userDao.getUserDataByUid(session.uid);
        if (!userData) {
            next(null, {
                code: code.REQUEST_DATA_ERROR
            });
            return;
        }

        // 查询会员数据

        if (msg.type != 1) {
            let memberUserData = await userDao.getUserDataByUid(msg.memberUid);
            if (!msg.type && !memberUserData) {
                next(null, {
                    code: code.USER_IN_ROOM_DATA_LOCKED
                });
                return;
            }
            // 判断是否在联盟中
            let userUnionInfoItem = memberUserData.unionInfo.find(function (element) {
                return element.unionID === msg.unionID;
            });
            if (!userUnionInfoItem) {
                next(null, {
                    code: code.PERMISSION_NOT_ENOUGH
                });
                return;
            }

            if (unionData.ownerUid !== session.uid && !userUnionInfoItem.partner && !userUnionInfoItem.manager) {
                next(null, {
                    code: code.PERMISSION_NOT_ENOUGH
                });
                return;
            }
        }

        // logger.error(`updateUserFixScore msg = ${JSON.stringify(msg)} sessionUid = ${session.uid}`);
        let fixScoreRate = msg.fixScoreRate || 0;
        let rebateRate = msg.rebateRate || 0;
        let ticketRate = msg.ticketRate || 0;
        // 更新分数限制
        let matchData = {
            uid: msg.memberUid,
            "unionInfo.unionID": msg.unionID
        }
        if (msg.type == 1) {
            matchData = {
                unionInfo: {
                    '$elemMatch':
                    {
                        "partner": true, 'spreaderID': session.uid, unionID: msg.unionID, fixScoreRate: { '$eq': 0 }, rebateRate: { '$eq': 0 }, ticketRate: { '$eq': 0 }
                    }
                }
            };
        }
        let newMemberData = await commonDao.updateAllData('userModel', matchData, {
            "unionInfo.$.fixScoreRate": fixScoreRate,
            "unionInfo.$.rebateRate": rebateRate,
            "unionInfo.$.ticketRate": ticketRate
        });
        if (!!newMemberData.frontendId) userInfoServices.updateUserDataNotify(newMemberData.uid, newMemberData.frontendId, {
            unionInfo: newMemberData.unionInfo
        }).catch(e => {
            logger.error(e)
        });

        let result = {
            code: code.OK,
            'fixScoreRate': fixScoreRate,
            'rebateRate': rebateRate,
            'ticketRate': ticketRate,
        };
        next(null, result);



    } catch (e) {
        logger.error(`[updateUserFixScore]` + e.stack);
        next(null, {
            code: 500
        });
    }
};
